2

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.

2 Answers 2

3

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 ]
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0
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
            }
        },

    ]



);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.