Count array elements that matches condition

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

Leave a Comment