计算符合条件的数组元素 [英] Count array elements that matches condition

查看:60
本文介绍了计算符合条件的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a mongoDB collection called "conference" with an array of participants as below :

[
  {
    "_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,
  },
  ...
]

我尝试了以下请求,但该请求不起作用:

I tried the request below but it's not working :

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

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

How is it possible to count "participant" array elements that match {"origin" : "internal"} and {"origin" : "external"} ?

推荐答案

您需要使用

You need to use $filter aggregation to filter out the external origin and internal origin along with the $size aggregation to calculate the length of the arrays.

类似这样的东西

db.collection.aggregate([
  { "$addFields": {
    "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
  }
]

这篇关于计算符合条件的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆