I have a problem where I want to get the number of occurences of a certain element in an array as i group them. Here is my schema:
{
"name": "John Doe",
"age": 20,
"address": "Nasipit, Talamban, Cebu City, Cebu",
"visitors": [
{
"_id": {
"$oid": "5de5a8271a91ca42fc5fc593"
},
"firstname": "Jane Doe",
"lastname": "Tanilon",
"address": "California",
"date": "December 3rd 2019, 8:11:19 am"
},
{
"_id": {
"$oid": "5de5a8271a91ca42fc5fc593"
},
"firstname": "Nice",
"lastname": "One",
"address": "California",
"date": "December 3rd 2019, 8:11:19 am"
}
]
}
I tried making to group them:
db.visitors.aggregate({
$group: {_id: '$visitors.address',count:{$sum:1}}
})
And the result is :
{ "_id" : [ "California", "California"], "count" : 1 }
And I want to count occurences of California in the array like this one:
{ "_id" : "California, "count" : 2 }
Expression '$visitors.address' returns an array while you need to count visitors array documents separately. To do that you need to $unwind that array before running $group:
db.visitors.aggregate([
{ $unwind: "$visitors" },
{
$group: {_id: '$visitors.address',count:{$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