MongoDB query to limit the returning values of a field?

To limit the returning values of a field in MongoDB, use the $slice operator in the projection parameter of the find() method. This is particularly useful for limiting array elements returned in query results.

Syntax

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

Sample Data

db.demo594.insertOne({
    id: 1,
    details: [
        { Name: "Chris", Age: 21 },
        { Name: "Bob", Age: 20 },
        { Name: "David", Age: 23 },
        { Name: "Sam", Age: 22 }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e933459fd2d90c177b5bcdd")
}

View All Documents

db.demo594.find();
{
    "_id": ObjectId("5e933459fd2d90c177b5bcdd"),
    "id": 1,
    "details": [
        { "Name": "Chris", "Age": 21 },
        { "Name": "Bob", "Age": 20 },
        { "Name": "David", "Age": 23 },
        { "Name": "Sam", "Age": 22 }
    ]
}

Example: Limit Array Elements

To return only the first element from the details array ?

db.demo594.find({}, { "details": { "$slice": 1 } });
{
    "_id": ObjectId("5e933459fd2d90c177b5bcdd"),
    "id": 1,
    "details": [
        { "Name": "Chris", "Age": 21 }
    ]
}

Key Points

  • $slice works only with array fields in the projection stage.
  • Use positive numbers to get elements from the beginning, negative numbers from the end.
  • You can combine $slice with other projection operators to include/exclude specific fields.

Conclusion

The $slice operator effectively limits array field values in MongoDB query results. Use it in the projection parameter to control how many array elements are returned, optimizing query performance and reducing data transfer.

Updated on: 2026-03-15T03:46:43+05:30

222 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements