MongoDB query to get only a specific number of elements

To return only a specific number of elements from an array field in MongoDB, use aggregate() with the $slice operator in a $project stage.

Syntax

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

Create Sample Data

db.demo75.insertOne({
    "Name": ["Sam", "Mike", "Carol", "David", "Bob", "John"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2bcd7671bf0181ecc42278")
}

Display all documents from the collection ?

db.demo75.find();
{
    "_id": ObjectId("5e2bcd7671bf0181ecc42278"),
    "Name": ["Sam", "Mike", "Carol", "David", "Bob", "John"]
}

Example: Get First 4 Elements

Using $slice to return only the first 4 elements from the Name array ?

db.demo75.aggregate([
    {
        $project: {
            Name: { $slice: [ "$Name", 4 ] }
        }
    }
]);
{
    "_id": ObjectId("5e2bcd7671bf0181ecc42278"),
    "Name": ["Sam", "Mike", "Carol", "David"]
}

Key Points

  • The $slice operator works within the $project stage of aggregation.
  • Specify the field name with "$" prefix and the number of elements to return.
  • Use positive numbers to get elements from the beginning of the array.

Conclusion

Use aggregate() with $slice in a $project stage to limit array elements returned. This approach is efficient for extracting specific portions of array fields without modifying the original document.

Updated on: 2026-03-15T01:50:53+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements