Reputation: 178
I have a data set like this
{name: john,
age:20,
....
}
{name: sally,
age: 40
...
}
{name: sally,
age: 50
...
}
What mongo query could I issue to get back every unique value for "name". So simply it would return 'john' and 'sally'
Upvotes: 2
Views: 2542
Reputation: 103445
The easiest way to get every unique value for "name" is by using the distinct()
method on the collection which will query the distinct values for a specified field across a single collection and returns the results in an array. Thus use it as
var distinctNames = db.collection.distinct("name");
printjson(distinctNames);
Sample Output:
[ "sally", "john" ]
Then another way, though not as simple and straightforward as the above, is to use the aggregation framework where you use the $group
pipeline stage to group the documents by the name key and outputs to the next stage a document for each distinct grouping.
With the cursor
returned from the aggregate()
method, you can then use its map()
method to create the desired final array. The following mongo shell demonstration describes the above concept:
var distinctNames = db.collection.aggregate([
{
"$group": {
"_id": "$name"
}
}
]).map(function (r){ return r._id; });
printjson(distinctNames);
Sample Output:
[ "sally", "john" ]
Upvotes: 2