tom10271
tom10271

Reputation: 4647

How to select and count distinct value of embedded array of collection in MongoDB?

Collection A have:

[
    {
        name: 'peter',
        types: ['human', 'male', 'young']
    },
    {
        name: 'mice',
        types: ['male', 'young']
    },
    {
        name: 'hen',
        types: ['female', 'old']
    }
]

I know how to get all distinct values of types but how to get its no. of appearance. How to extract it with Mongo query?

It would be great if you can show the solution in Doctrine QueryBuilder way.

Thanks

Upvotes: 0

Views: 934

Answers (1)

profesor79
profesor79

Reputation: 9473

with aggregation framework you can sum apperance of all array elements using query provide below:

db.collection.aggregate([{
            $project : {
                _id : 0,
                types : 1
            }
        }, {
            $unwind : "$types"
        }, {
            $group : {
                _id : "$types",
                count : {
                    $sum : 1
                }
            }
        }

    ])

and output:

{
    "_id" : "human",
    "count" : 1
}, {
    "_id" : "old",
    "count" : 1
}, {
    "_id" : "male",
    "count" : 2
}, {
    "_id" : "young",
    "count" : 2
}, {
    "_id" : "female",
    "count" : 1
}

Upvotes: 2

Related Questions