Set MongoDB $slice with a range?

MongoDBDatabaseBig Data Analytics

To set slice along with a range, use the $slice operator with parameters. These parameters are to be set for beginning position of the elements to be fetched and the 2nd parameter is for range. 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 a collection with the help of find() method −

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

This will produce the following output −

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

Following is the query to set slice with a range −

> db.demo54.find({}, { "ListOfValues": { $slice: [5,3]}}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e27151ecfb11e5c34d89914"),
   "ListOfValues" : [
      535,
      524,
      423
   ]
}
raja
Published on 03-Apr-2020 16:05:10
Advertisements