MongoDB Aggregation to slice array inside array

To slice an array inside another array in MongoDB, use the aggregate() method with $addFields, $map, and $slice operators. This allows you to limit the number of elements returned from nested arrays.

Syntax

db.collection.aggregate([
    { $addFields: {
        "arrayField": {
            $map: {
                "input": "$arrayField",
                "as": "element",
                "in": {
                    "field1": "$$element.field1",
                    "nestedArray": { $slice: [ "$$element.nestedArray", count ] }
                }
            }
        }
    }}
]);

Sample Data

db.demo111.insertOne({
    "_id": 101,
    "Name": "Chris",
    "Details": [
        {
            "_id": 101,
            "Score": 78,
            "Subjects": [
                {
                    "_id": "10001",
                    "SubjectName": "MySQL"
                },
                {
                    "_id": "10003",
                    "SubjectName": "MongoDB"
                }
            ]
        },
        {
            "_id": 102,
            "Score": 87,
            "Subjects": [
                {
                    "_id": "10004",
                    "SubjectName": "Java"
                }
            ]
        }
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Example: Slice First Element from Subjects Array

To limit each Subjects array to only the first element, use $slice with count 1 ?

db.demo111.aggregate([
    { $addFields: {
        "Details": {
            $map: {
                "input": "$Details",
                "as": "out",
                "in": {
                    "_id": "$$out._id",
                    "Score": "$$out.Score",
                    "Subjects": { $slice: [ "$$out.Subjects", 1 ] }
                }
            }
        }
    }}
]);
{
    "_id": 101,
    "Name": "Chris",
    "Details": [
        { "_id": 101, "Score": 78, "Subjects": [ { "_id": "10001", "SubjectName": "MySQL" } ] },
        { "_id": 102, "Score": 87, "Subjects": [ { "_id": "10004", "SubjectName": "Java" } ] }
    ]
}

Key Points

  • $map iterates through each element in the outer Details array
  • $slice limits the number of elements returned from the nested Subjects array
  • Use $$element to reference fields within the mapped element

Conclusion

Combine $addFields, $map, and $slice to effectively slice arrays within arrays. The $map operator processes each outer array element, while $slice controls the number of nested array elements returned.

Updated on: 2026-03-15T01:56:11+05:30

496 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements