
- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document
- MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
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 Articles
- Display the last two values from field with MongoDB
- Get Distinct Values with Sorted Data in MongoDB?
- MongoDB query to get last inserted document?
- How to get the last N records in MongoDB?
- Get the length of distinct values in an array with MongoDB
- MongoDB aggregation to get two documents with the least marks
- 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 all the records with two different values in another column with MySQL
- Get all the MongoDB documents but not the ones with two given criteria’s?
- Update the last row with search criteria in MongoDB?
- Get the duplicate values of a field in MongoDB?
- MongoDB query to get only distinct values
- Query on the last object of an array with MongoDB

Advertisements