Aggregate a $slice to get an element in exact position from a nested array in MongoDB?

To get an element from an exact position in a nested array using MongoDB's aggregation framework, use the $slice operator within a $project stage to extract specific elements by their index position.

Syntax

db.collection.aggregate([
    {
        $project: {
            "arrayField": { $slice: ["$arrayField", startIndex, numberOfElements] }
        }
    }
]);

Sample Data

db.exactPositionDemo.insertOne({
    "StudentName": "John",
    "StudentScores": [78, 98, 56, 45, 89]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd29a1c345990cee87fd883")
}

Let's verify our sample data ?

db.exactPositionDemo.find().pretty();
{
    "_id": ObjectId("5cd29a1c345990cee87fd883"),
    "StudentName": "John",
    "StudentScores": [78, 98, 56, 45, 89]
}

Case 1: Get Element at Index 0

Extract the first element (index 0) from StudentScores array ?

db.exactPositionDemo.aggregate([
    {
        $project: {
            "StudentScores": { $slice: ["$StudentScores", 0, 1] }
        }
    }
]);
{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [78] }

Case 2: Get Element at Index 1

Extract the second element (index 1) from StudentScores array ?

db.exactPositionDemo.aggregate([
    {
        $project: {
            "StudentScores": { $slice: ["$StudentScores", 1, 1] }
        }
    }
]);
{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [98] }

Key Points

  • $slice takes three parameters: [array, startIndex, numberOfElements]
  • StartIndex is zero−based (0 = first element, 1 = second element)
  • Setting numberOfElements to 1 returns exactly one element at the specified position
  • The result is always returned as an array, even for a single element

Conclusion

The $slice operator in aggregation pipelines provides precise control over array element extraction. Use startIndex to specify position and numberOfElements to control how many elements to return from that position.

Updated on: 2026-03-15T01:02:10+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements