

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] }
- Related Questions & Answers
- Display the last two values from field with MongoDB
- MongoDB aggregation to get two documents with the least marks
- How to get the last N records in MongoDB?
- Get Distinct Values with Sorted Data in MongoDB?
- MongoDB query to get last inserted document?
- Get the length of distinct values in an array with MongoDB
- Get all the records with two different values in another column with MySQL
- Update the last row with search criteria in MongoDB?
- How to get only values in arrays with MongoDB aggregate?
- Get distinct record values in MongoDB?
- Get the sum of last 3 digits from all the values in a column with MySQL
- Get the duplicate values of a field in MongoDB?
- Query on the last object of an array with MongoDB
- How to get the max of two values MySQL?
- Get all the MongoDB documents but not the ones with two given criteria’s?
Advertisements