MongoDB slice array in populated field?


To slice array, use a $slice operator in MongoDB. Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo503.find().pretty();

This will produce the following output −

{ "_id" : 1, "Name" : "John", "Subject" : [ "MySQL", "Java", "C" ] }
{
   "_id" : 2,
   "Name" : "David",
   "Subject" : [
      "MongoDB",
      "C++",
      "Python"
   ]
}

Following is the query to slice array in the populated field −

> db.demo503.find({_id:2}, { 'Subject': { $slice: -1 }});

This will produce the following output −

{ "_id" : 2, "Name" : "David", "Subject" : [ "Python" ] }

Updated on: 13-May-2020

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements