Reputation: 55
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 }
Upvotes: 3
Views: 80
Reputation: 14287
The following aggregation query counts all the occurances of "California" in all documents.
var INPUT_PARAM = "California"
db.test.aggregate( [
{
$unwind: "$visitors"
},
{
$group: {
_id: null,
count: {
$sum: {
"$cond": [
{ "$eq": [ "$visitors.address", INPUT_PARAM ] },
1,
0
]
}
}
}
},
{
$project: {
_id: INPUT_PARAM,
count: 1
}
}
] )
The result is: { "count" : 3, "_id" : "California" }
, when the input documents are:
{ _id: 11,
"name": "John Doe",
"address": "Nasipit, Talamban, Cebu City, Cebu",
"visitors": [
{
"_id": 1,
"firstname": "Jane Doe",
"address": "California",
},
{
"_id": 2,
"firstname": "Nice",
"address": "California",
},
{"_id": 3,
"firstname": "Jack",
"address": "Texas",
}
]
},
{ _id: 22,
"name": "Miller",
"address": "14, North 5th St., New York",
"visitors": [
{
"_id": 95,
"firstname": "ABC",
"address": "California",
},
{ "_id": 96,
"firstname": "XYZ",
"address": "Maine",
}
]
}
Upvotes: 1
Reputation: 49945
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}}
}
])
Upvotes: 3