How to get the Count of Array in the Document

Hi Mates,

_id:60ed7ca7ba35360001d5d7e3

createdTime:1626176679084

members:

    Array

        1. 0:"758bd45b-0741-430b-ae3c-af0f1c2e42b7"

        2. 1:"b778749e-35b3-4b94-9b46-a145579a6b26"

        3. 2:"883dff93-0205-46de-9cf3-c9c364267667"

type:"savings"

state:"active"

I’ve documents like this in my DB Collection. I have to get the total of Members(Array) when the type is equal to Savings and State equal to Active. However, I managed to get the output like below.

{
            "total": 3
        },
        {
            "total": 3
        },
        {
            "total": 3
        },
        {
            "total": 4
        }

It’s returning me the size of members in each document. But, I want to get the grand total when the conditions meet the requirement.

Can you guys Suggest me the Aggregation Query ann Spring Boot Solution(If Possible)

You will need

with a

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.

2 Likes

Thanks a lot @MaBeuLux88.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.