Reputation: 29
I have some documents like :
{
"product" : [{
"name" : "apple",
"seller" : [
{
"name" : "Alice",
"gender" : 1
},
{
"name" : "Bob",
"gender" : 0
}
]
}, {
"name" : "anotherApple",
"seller" : [
{
"name" : "Bob",
"gender" : 0
}
]
}],
"date" : "someDay"
},
{
"product" : [{
"name" : "apple",
"seller" : [
{
"name" : "Alice",
"gender" : 1
},
{
"name" : "CName",
"gender" : 0
}
]
}],
"date" : "someDay"
}
And I wanna count the number of one seller's bills, in this case , which is supposed to be :
{
"Alice" : 2,
"Bob" : 1,
"CName" : 1
}
I have tried some ways such like unwind seller
in product
but none of them works. How can I do this?
Upvotes: 0
Views: 32
Reputation: 2484
I used addToSet
to have a list of ids.
And count them with $size
in a project
db.collection.aggregate({
"$unwind": "$product"
},
{
"$unwind": "$product.seller"
},
{
$group: {
_id: "$product.seller.name",
list_ids: {
"$addToSet": "$_id"
}
}
},
{
$project: {
"_id": 1,
"size": {
$size: "$list_ids"
}
}
})
Witch gives me
[
{
"_id": "CName",
"size": 1
},
{
"_id": "Alice",
"size": 2
},
{
"_id": "Bob",
"size": 1
}
]
Try it here
Upvotes: 2