Muirik
Muirik

Reputation: 6289

Mongoose Query to Find Unique Values

In my MongoDB backend I want to create an endpoint that returns all the unique values for a property called department. Now, if I were doing this in IntelliShell I would just do something like:

db.staffmembers.distinct( "department" )

This will return an array of all the values for department.

But how do you return all unique values within a Mongoose find() query like this one?

Staffmember.find({ name: 'john', age: { $gte: 18 }});

In other words, what would the syntax look like if I want to use a find() like above, to return all unique values for department within the "staffmembers" collection?

Upvotes: 2

Views: 8492

Answers (2)

SDK4551
SDK4551

Reputation: 109

We can use find and distinct like this for the above scenario. Aggregate might be a little overkill. I have tried both the solutions below.

Staffmember.find({name: 'john', age: {$gte: 18}}).distinct('department', 
   function(error, departments) {
       // departments is an array of all unique department names
   }
);

Staffmember.distinct('department', {name:'john', age:{ $gte: 18 }},
   function(error, departments) {
       // departments is an array of all unique department names
   }
);

This link just nails it with all different possibilities: How do I query for distinct values in Mongoose?

Upvotes: 0

mickl
mickl

Reputation: 49945

You can use .aggregate() and pass your condition into $match stage and then use $addToSet within $group to get unique values.

let result = await Staffmember.aggregate([
    { $match: { name: 'john', age: { $gte: 18 }} },
    { $group: { _id: null, departments: { $addToSet: "$department" } } }
]);

Upvotes: 8

Related Questions