Get the last two values with MongoDB


To get the last two values, use MongoDB $slice. Let us create a collection with documents −

> db.demo173.insertOne({"ListOfValues":[10,40,100,560,700,900]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e383a4f9e4f06af551997e4")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e383a4f9e4f06af551997e4"),
   "ListOfValues" : [ 10, 40, 100, 560, 700, 900 ]
}

Following is the query to get the last two values −

> db.demo173.find({}, { "ListOfValues": { "$slice": -2 } } );

This will produce the following output −

{ "_id" : ObjectId("5e383a4f9e4f06af551997e4"), "ListOfValues" : [ 700, 900 ] }

Updated on: 30-Mar-2020

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements