MongoDB - Sum of multiple array sizes in a document

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "totalDoctors": {
        "$sum": {
          "$cond": {
            "if": {"$isArray": ["$doctors"]},
            "then": {"$size": "$doctors"},
            "else": 0
          }
        }
      },
      "totalNurses": {
        "$sum": {
          "$cond": {
            "if": {"$isArray": ["$nurses"]},
            "then": {"$size": "$nurses"},
            "else": 0
          }
        }
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "nPersons": {
        "$add": ["$totalDoctors","$totalNurses"
        ]
      }
    }
  }
])
Topics: MongoDB

Related Code Examples