我有一个问题,我想要获取数组中某个元素出现的次数,而且还要将它们分组。
这是我的架构:
{
"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"
}
]
}
我试着将它们分组:
db.visitors.aggregate({
$group: {_id: '$visitors.address',count:{$sum:1}}
})
结果是:
{ "_id" : [ "加利福尼亚州", "加利福尼亚州"], "count" : 1 }
我想要像这个数组一样计算“加利福尼亚州”的出现次数:
{ "_id" : "加利福尼亚州", "count" : 2 }