 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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
 