How do you limit an array sub-element in MongoDB?

You can use $slice operator to limit array elements in MongoDB query results. The $slice operator controls how many elements from an array field are returned in the projection.

Syntax

db.collection.find(
    {},
    { "arrayField": { $slice: N } }
)

Where N can be:

  • Positive number: Returns first N elements
  • Negative number: Returns last N elements
  • [skip, limit]: Skips elements and limits result

Sample Data

db.limitAnArrayDemo.insertOne({
    _id: 101,
    "PlayerName": "Bob",
    "PlayerDetails": {Age: 23, isStudent: true},
    "PlayerGameScores": [234, 5767, 58, 67, 78, 90, 1002, 576, 68, 45, 23, 45, 678, 89, 78]
});

Example 1: Limit to Last 10 Elements

Display only the last 10 scores from PlayerGameScores array ?

db.limitAnArrayDemo.find(
    {},
    {
        PlayerName: 1,
        PlayerDetails: 1,
        PlayerGameScores: { $slice: -10 }
    }
);
{
    "_id": 101,
    "PlayerName": "Bob",
    "PlayerDetails": {
        "Age": 23,
        "isStudent": true
    },
    "PlayerGameScores": [
        90, 1002, 576, 68, 45, 23, 45, 678, 89, 78
    ]
}

Example 2: Limit to First 5 Elements

db.limitAnArrayDemo.find(
    {},
    { PlayerGameScores: { $slice: 5 } }
);
{
    "_id": 101,
    "PlayerName": "Bob",
    "PlayerDetails": { "Age": 23, "isStudent": true },
    "PlayerGameScores": [234, 5767, 58, 67, 78]
}

Key Points

  • $slice works only in projection (second parameter of find())
  • Negative values return elements from the end of the array
  • Positive values return elements from the beginning
  • Original array in the database remains unchanged

Conclusion

The $slice operator provides an efficient way to limit array elements in query results. Use negative values for last N elements and positive values for first N elements in your projections.

Updated on: 2026-03-15T00:39:24+05:30

857 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements