F
F
Fengol2019-02-26 18:08:59
MongoDB
Fengol, 2019-02-26 18:08:59

How to choose one document from the set?

Marvel.create({name: 'Superman', type: 'superhero'});
Marvel.create({name: 'Superman', type: 'superhero'});
Marvel.create({name: 'Batman', type: 'superhero'});
Marvel.create({name: 'Batman', type: 'superhero'});
Marvel.create({name: 'Joker', type: 'supervillain'});
Marvel.create({name: 'Superman', type: 'supervillain'});

How to write a query in mongoose to get -
[
    {name: 'Superman', type: 'superhero'},
    {name: 'Batman', type: 'superhero'}
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
Urukhayy, 2019-02-27
@Fengol

Marvel.aggregate( [
  {$group: {_id : {name : '$name', type:'$type'}}},
  {$project : {name: '$_id.name', type: '$_id.type', _id : 0}}
], function (err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
        }
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question