Tutorialspoint

1 Answer
George John

Let us first create a collection with documents −

> db.numberOfValuesDemo.insertOne({"Values":[100,200,300,900,1000,98]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefb736ef71edecf6a1f6ab")
}

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

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

Output

{
   "_id" : ObjectId("5cefb736ef71edecf6a1f6ab"),
   "Values" : [
      100,
      200,
      300,
      900,
      1000,
      98
   ]
}

Following is the query to get the last two values.

Here, we have used -ve sign under $slice −

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

Output

{ "_id" : ObjectId("5cefb736ef71edecf6a1f6ab"), "Values" : [ 1000, 98 ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.