Set MongoDB $slice with a range?

To set slice with a range in MongoDB, use the $slice operator with two parameters: the starting position and the number of elements to return. This allows you to extract a specific range of elements from an array field.

Syntax

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

Sample Data

Let us create a collection with documents ?

db.demo54.insertOne({
    "ListOfValues": [100, 2030, 5353, 7364, 635, 535, 524, 423, 2434, 1323, 799874, 90]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e27151ecfb11e5c34d89914")
}

Display all documents from the collection ?

db.demo54.find().pretty();
{
    "_id": ObjectId("5e27151ecfb11e5c34d89914"),
    "ListOfValues": [
        100,
        2030,
        5353,
        7364,
        635,
        535,
        524,
        423,
        2434,
        1323,
        799874,
        90
    ]
}

Example: Extract 3 Elements Starting from Index 5

Following is the query to set slice with a range ?

db.demo54.find({}, { "ListOfValues": { $slice: [5, 3] } }).pretty();
{
    "_id": ObjectId("5e27151ecfb11e5c34d89914"),
    "ListOfValues": [
        535,
        524,
        423
    ]
}

How It Works

In $slice: [5, 3]:

  • 5 is the starting index (0-based indexing)
  • 3 is the number of elements to return
  • Returns elements at positions 5, 6, and 7 from the original array

Conclusion

The $slice operator with range parameters [startIndex, count] efficiently extracts a specific subset of array elements. Use it in projection to limit array data returned from MongoDB queries.

Updated on: 2026-03-15T02:50:34+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements