Let's say I have the following documents in collection:
{
"family": "Smith",
"children": [
{
"child_name": "John"
},
{
"child_name": "Anna"
},
]
}
{
"family": "Williams",
"children": [
{
"child_name": "Anna"
},
{
"child_name": "Kevin"
},
]
}
Now I want to get somehow the following list of unique child names cross all families:
[ "John", "Anna", "Kevin" ]
Structure of result might be different. How to achieve that in MongoDB? Should be something simple but I can't figure out. I tried aggregate() function on collection but then I don't know how to apply distinct() function.
To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.
MongoDB – Distinct() Method In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.
You can use $addToSet with the aggregation framework to count distinct objects. Not a generic solution, if you have a large number of unique zip codes per result, this array would be very large.
Definition. distinct. Finds the distinct values for a specified field across a single collection. distinct returns a document that contains an array of the distinct values. The return document also contains an embedded document with query statistics and the query plan.
You can just do:
db.collection.distinct("children.child_name");
In your case it returns:
[ "John", "Anna", "Kevin" ]
with the help aggregation framework:
db.collection.aggregate([{$unwind:'$children'}, {$group:{_id:'$children.child_name'}}])
or more interest ;) with frequency of name:
db.collection.aggregate([{$unwind:'$children'}, {$group:{_id:'$children.child_name', freq:{$sum:1}}}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With