计算符合条件的数组元素

时间:2018-09-04 13:40:15

标签: database mongodb mongodb-query aggregation-framework

我有一个名为“会议”的mongoDB集合,参与者如下:

[
  {
    "_id" : 5b894357a0c84d5a5d221f25, 
    "conferenceName" : "myFirstConference",
    "startDate" : 1535722327, 
    "endDate" : 1535722420,
    "participants" : [
        {
            "name" : "user1", 
            "origin" : "internal", 
            "ip" : "192.168.0.2"
        },
        {
            "name" : "user2", 
            "origin" : "external", 
            "ip" : "172.20.0.3"
        }, 
    ]
  },
  ...
]

我想得到以下结果:

[
  {
     "conferenceName" : "myFirstConference",
     "startDate" : 1535722327, 
     "endDate" : 1535722420,
     "internalUsersCount" : 1
     "externalUsersCount" : 1,
  },
  ...
]

我尝试了以下请求,但没有成功:

db.getCollection("conference").aggregate([
   {
     $addFields: {
       internalUsersCount : {
            $size : { "$participants" : {$elemMatch : { origin : "internal" }}}
         },
       externalUsersCount : {
            $size : { "$participants" : {$elemMatch : { origin : "external" }}}
         }         
     }
   }
])

如何计算与 {“ origin”:“ internal”} {“ origin”:“ external”} 相匹配的“参与者”数组元素?

1 个答案:

答案 0 :(得分:4)

您需要使用$filter聚合来过滤externalinternal的原点以及$size聚合来计算数组的长度。

类似这样的东西

db.collection.aggregate([
  { "$project": {
    "conferenceName": 1,
    "startDate": 1,
    "endDate": 1,
    "internalUsersCount": {
      "$size": {
        "$filter": {
          "input": "$participants",
          "as": "part",
          "cond": { "$eq": ["$$part.origin", "internal"]}
        }
      }
    },
    "externalUsersCount": {
      "$size": {
        "$filter": {
          "input": "$participants",
          "as": "part",
          "cond": { "$eq": ["$$part.origin", "external"] }
        }
      }
    }
  }}
])

输出

[
  {
    "conferenceName": "myFirstConference",
    "endDate": 1535722420,
    "externalUsersCount": 1,
    "internalUsersCount": 1,
    "startDate": 1535722327
  }
]