组中数组内部元素的Mongodb计数

问题描述 投票:2回答:1

我有一个问题,当我将它们分组时,我想获取数组中某个元素的出现次数。这是我的架构:

{
   "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”:[“ California”,“ California”],“ count”:1}

而且我想在像这样的数组中计算加利福尼亚的出现次数:

{“ _id”:“加利福尼亚,” count“:2}

mongodb mongodb-query aggregation-framework
1个回答
0
投票

表达式'$visitors.address'返回一个数组,而您需要分别计算访问者数组文档。为此,您需要在运行$unwind之前先$group该阵列:

db.visitors.aggregate([
    { $unwind: "$visitors" },
    {
        $group: {_id: '$visitors.address',count:{$sum:1}}
    }
])

推荐问答