Reputation: 4647
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
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