Get the last two values with MongoDB

MongoDBDatabaseBig Data Analytics

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 ] }
raja
Published on 30-Mar-2020 12:56:33
Advertisements