MongoDB slice array in populated field?

To slice arrays in MongoDB, use the $slice operator in the projection part of your query. This allows you to return only a portion of an array field from documents.

Syntax

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

Where count can be:

  • Positive number: Returns first N elements
  • Negative number: Returns last N elements
  • [skip, limit]: Skips elements and returns limited count

Sample Data

db.demo503.insertMany([
    {_id:1, Name:"John", Subject:["MySQL","Java","C"]},
    {_id:2, Name:"David", Subject:["MongoDB","C++","Python"]}
]);
{
  "acknowledged": true,
  "insertedIds": { "0": 1, "1": 2 }
}

Display All Documents

db.demo503.find();
{ "_id": 1, "Name": "John", "Subject": [ "MySQL", "Java", "C" ] }
{ "_id": 2, "Name": "David", "Subject": [ "MongoDB", "C++", "Python" ] }

Example: Get Last Element

Get only the last subject for David ?

db.demo503.find({_id:2}, { 'Subject': { $slice: -1 }});
{ "_id": 2, "Name": "David", "Subject": [ "Python" ] }

More Examples

Get First Two Elements

db.demo503.find({_id:1}, { 'Subject': { $slice: 2 }});
{ "_id": 1, "Name": "John", "Subject": [ "MySQL", "Java" ] }

Skip First Element, Get Next Two

db.demo503.find({_id:2}, { 'Subject': { $slice: [1, 2] }});
{ "_id": 2, "Name": "David", "Subject": [ "C++", "Python" ] }

Conclusion

The $slice operator efficiently limits array elements in query results. Use negative values for last elements, positive for first elements, and [skip, limit] for precise range selection.

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

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements