Skip to content

Mongodb – Get the last record from collection

Advertisement

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

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply

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


Back to top