how to get last insert data to first insert data from mongodb

Viewed 25

I am having a problem finding data from MongoDB. I am trying to get data last inset first to insert data. if you know how I can get data effortless please help me? below the MongoDB data, I want to show this data on my website last inset to first insert data. I hope so I will get my answer. thank you.

{ "_id" : ObjectId("5cefb17eef71edecf6a1f6a8"), "Name" : "John" }
{ "_id" : ObjectId("5cefb181ef71edecf6a1f6a9"), "Name" : "Chris" }
{ "_id" : ObjectId("5cefb185ef71edecf6a1f6aa"), "Name" : "Robert" }

1 Answers

To get your data sorted from the last inserted document you need to use sort() function.

db.collection.find({}).sort({_id:-1})

.sort({_id:-1}) sorts the data in a collection from Last to First inserted.

Related