- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Articles
- MongoDB collection query to exclude some fields in find()?
- MongoDB query to rename a collection?
- Query on the last object of an array with MongoDB
- Query MongoDB collection starting with _?
- MongoDB query to find a specific city record from a collection
- MongoDB query to get last inserted document?
- MongoDB: How to query a collection named “version”?
- MongoDB query to remove entire array from collection?
- MongoDB query to remove entire data from a collection
- MongoDB query to pull array element from a collection?
- How do I query a MongoDB collection?
- MongoDB query to add a document in an already created collection
- MongoDB query for capped sub-collection in an array
- MongoDB query in object of arrays
- MongoDB query to find data from an array inside an object?

Advertisements