MongoDB query to slice only one element of array

To slice only one element of an array in MongoDB, use the $slice operator in the projection stage of a query. This operator allows you to return a specific number of array elements from the beginning or end of an array.

Syntax

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

Where N is the number of elements to return (positive for first N elements, negative for last N elements).

Sample Data

db.demo579.insertOne({
    "_id": 101,
    "details": { "FirstName": "John" },
    "Marks": [ 56, 78, 90, 34, 45, 74 ]
});
{ "acknowledged": true, "insertedId": 101 }

Example: Slice First Element

To get only the first element from the Marks array ?

db.demo579.find(
    {},
    { 
        "Marks": { $slice: 1 }, 
        "details": 0, 
        "_id": 0 
    }
);
{ "Marks": [ 56 ] }

Example: Slice Last Element

To get only the last element from the array ?

db.demo579.find(
    {},
    { 
        "Marks": { $slice: -1 }, 
        "details": 0, 
        "_id": 0 
    }
);
{ "Marks": [ 74 ] }

Key Points

  • $slice: 1 returns the first element of the array.
  • $slice: -1 returns the last element of the array.
  • Use 0 in projection to exclude unwanted fields from the result.

Conclusion

The $slice operator provides an efficient way to return specific portions of arrays in MongoDB queries. Use positive values for elements from the beginning and negative values for elements from the end.

Updated on: 2026-03-15T03:44:04+05:30

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements