database

mongodb

mongodb-query

aggregation-framework

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

I would like to get the following result :

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

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

Solution 1

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