Limit number of values in a field using MongoDB?

To limit the number of values in a field using MongoDB, use the $slice projection operator. This operator allows you to return only a specified number of elements from an array field.

Syntax

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

Sample Data

Let us first create a collection with documents ?

db.numberOfValuesDemo.insertOne({
    "Values": [100, 200, 300, 900, 1000, 98]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cefb736ef71edecf6a1f6ab")
}

Display all documents from the collection ?

db.numberOfValuesDemo.find().pretty();
{
    "_id": ObjectId("5cefb736ef71edecf6a1f6ab"),
    "Values": [
        100,
        200,
        300,
        900,
        1000,
        98
    ]
}

Example: Limit to First 2 Values

The following query limits the Values array to return only the first 2 elements ?

db.numberOfValuesDemo.find(
    {},
    { "Values": { "$slice": 2 } }
);
{
    "_id": ObjectId("5cefb736ef71edecf6a1f6ab"),
    "Values": [100, 200]
}

Additional Examples

Last 3 Elements

db.numberOfValuesDemo.find(
    {},
    { "Values": { "$slice": -3 } }
);
{
    "_id": ObjectId("5cefb736ef71edecf6a1f6ab"),
    "Values": [900, 1000, 98]
}

Skip and Limit

Skip first 2 elements and return next 2 ?

db.numberOfValuesDemo.find(
    {},
    { "Values": { "$slice": [2, 2] } }
);
{
    "_id": ObjectId("5cefb736ef71edecf6a1f6ab"),
    "Values": [300, 900]
}

Key Points

  • Positive number: Returns first N elements from the beginning
  • Negative number: Returns last N elements from the end
  • Array format [skip, limit]: Skips elements and returns the specified count

Conclusion

The $slice operator provides flexible array limiting capabilities in MongoDB projections. Use positive values for first elements, negative for last elements, or array syntax to skip and limit specific ranges.

Updated on: 2026-03-15T01:27:20+05:30

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements