Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: How to get distinct list of sub-document field values?

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.

like image 338
vladimir Avatar asked Apr 22 '13 19:04

vladimir


People also ask

How can I get distinct values from a field in MongoDB?

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.

Which command gives all the distinct values in MongoDB?

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.

How do I use distinct aggregation in MongoDB?

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.

What is MongoDB distinct?

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.


2 Answers

You can just do:

db.collection.distinct("children.child_name");

In your case it returns:

[ "John", "Anna", "Kevin" ]
like image 82
Asya Kamsky Avatar answered Oct 06 '22 15:10

Asya Kamsky


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}}}])
like image 23
Vladimir Muzhilov Avatar answered Oct 06 '22 17:10

Vladimir Muzhilov