Count array elements that matches condition

后端 未结 1 1240
感动是毒
感动是毒 2020-12-02 02:34

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

[
  {
    \"_id\" : 5b894357a0c84d5a5d221f25, 
    \"conferenceNa         


        
相关标签:
1条回答
  • 2020-12-02 02:59

    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.

    Something like this

    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"] }
            }
          }
        }
      }}
    ])
    

    Output

    [
      {
        "conferenceName": "myFirstConference",
        "endDate": 1535722420,
        "externalUsersCount": 1,
        "internalUsersCount": 1,
        "startDate": 1535722327
      }
    ]
    
    0 讨论(0)
提交回复
热议问题