- Trending Categories
- 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
In MongoDB, what is the most efficient way to get the first and last document?
To get the first and last document in MongoDB, use aggregate() along with $first and $last respectively. Let us create a collection with documents −
> db.demo73.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e29c41b71bf0181ecc4226c") } . > db.demo73.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e29c41e71bf0181ecc4226d") } > db.demo73.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e29c42271bf0181ecc4226e") }
Display all documents from a collection with the help of find() method −
> db.demo73.find();
This will produce the following output −
{ "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" } { "_id" : ObjectId("5e29c41e71bf0181ecc4226d"), "Name" : "Bob" } { "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David" }
Following is the way to get the first and last document−
> db.demo73.aggregate({ ... $group: { ... _id: null, ... first: { $first: "$$ROOT" }, ... last: { $last: "$$ROOT" } ... } ... } ... );
This will produce the following output −
{ "_id" : null, "first" : { "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" }, "last" : { "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David" } }
Advertisements