Shambhavi_RB
Shambhavi_RB

Reputation: 121

How to find the size of an array within an array?

I have an array like:

{
"students": [
    [
        "5c8783f0927b1849b923a47b",
        "5c889c139af6b305e19cd17e",
        "5c89f1dc4dc6695c138cb2a4",
        "5cb0624945111f1c5fdf2527",
        "5caed95afd229a5c460e745b",
        "5cbeb926fac7143e261adaab"
    ],
    [
        "5c8783f0927b1849b923a47b",
        "5c889c139af6b305e19cd17e",
        "5c89f1dc4dc6695c138cb2a4"
    ],
    [
        "5c8783f0927b1849b923a47b",
        "5c89f1dc4dc6695c138cb2a4",
        "5cadc0452a00532a4c903c38"
    ],
    [
        "5c8783f0927b1849b923a47b"
    ]
          ]
}

I want to find the size of each array in the students array. Like this:

"count": [6, 3, 3, 1]

I have tried $map with $size

 aggregatePipe.push({
       $group: {
                    _id: { subjectId: "$subjectId" },
                    studentIds: { $push: "$students" },
                    count: { $push: { $map: { input: "$students", as: "student", in: { $size: "$student" } } } }
                }
            });

But I'm getting array of null values.

Upvotes: 2

Views: 51

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$students",

            }
        },

        // Stage 2
        {
            $project: {
                count: {
                    $size: '$students'
                }
            }
        },

        // Stage 3
        {
            $group: {
                _id: null,
                count: {
                    $push: '$count'
                }
            }
        },

        // Stage 4
        {
            $project: {
                _id: 0
            }
        },

    ]



);

Upvotes: 0

Ashh
Ashh

Reputation: 46491

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "students": {
      "$map": {
        "input": "$students",
        "in": { "$size": "$$this" }
      }
    }
  }}
])

Output

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "students": [ 6, 3, 3, 1 ]
  }
]

Upvotes: 3

Related Questions