![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to find last object in collection?
To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).
Let us first create a collection with documents −
> db.demo141.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c347fdf09dd6d08539ae") } > db.demo141.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c34bfdf09dd6d08539af") } > db.demo141.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c34ffdf09dd6d08539b0") } > db.demo141.insertOne({"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c352fdf09dd6d08539b1") }
Display all documents from a collection with the help of find() method −
> db.demo141.find();
This will produce the following output −
{ "_id" : ObjectId("5e31c347fdf09dd6d08539ae"), "Name" : "Chris" } { "_id" : ObjectId("5e31c34bfdf09dd6d08539af"), "Name" : "David" } { "_id" : ObjectId("5e31c34ffdf09dd6d08539b0"), "Name" : "Bob" } { "_id" : ObjectId("5e31c352fdf09dd6d08539b1"), "Name" : "Mike" }
Following is the query to find last object in collection −
> db.demo141.find().sort({_id:-1}).limit(1);
This will produce the following output −
{ "_id" : ObjectId("5e31c352fdf09dd6d08539b1"), "Name" : "Mike" }
Advertisements