How to get the Count of Array in the Document

Here is my attempt:

db.coll.insertMany([{members: [1,2,3]},{members: [4,5]},{members: [6]}])
...
db.coll.find().pretty()
[
  { _id: ObjectId("612e35b54e0a9383b784358c"), members: [ 1, 2, 3 ] },
  { _id: ObjectId("612e35b54e0a9383b784358d"), members: [ 4, 5 ] },
  { _id: ObjectId("612e35b54e0a9383b784358e"), members: [ 6 ] }
]

Using MongoDB Compass, I built this aggregation:

> db.coll.aggregate([
      {
        '$addFields': {
          'size': {
            '$size': '$members'
          }
        }
      }, {
        '$group': {
          '_id': null, 
          'members_count': {
            '$sum': '$size'
          }
        }
      }
    ])
[ { _id: null, members_count: 6 } ]

Of course, you can add the $match stage as the first stage to filter for {type:"savings", state: "active"}.

A screenshot from Compass to help understand the stage logic:

Cheers,
Maxime.

3 Likes