Skip to content

Mongodb – Get the last record from collection

Category
Databases
Covers
MongoDB
Versions & support
About MongoDB →

MongoDB find() method is used to select documents from a specified collection. It also set the cursor position to the selected document.

The default find() method gets the documents from the start of the collection. In some situations, we need to fetch the last record from a collection. Use the following query to get the last records from a MongoDB collection.

db.collection.find().limit(1).sort({$natural:-1}) 

The above query provides the single last record only, You can also fetch the multiple records from the end of the MongoDB collection.

You can set the number of records with limit() method as below:

db.collection.find().limit(5).sort({$natural:-1}) 

Thanks, Hope this quick how-to tutorial helps you to fulfill your requirements.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top