Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latest Document with respect to ObjectID timestamp Mongo

I am looking for the correct query that will get the latest inserted document in a mongo collection based on the ObjectID (while holds a time-stamp).

Is that a good method of getting the latest inserted document efficiency wise?

Thanks.

like image 589
DevilCode Avatar asked Jan 28 '15 12:01

DevilCode


1 Answers

Get last document in ObjectId from "primary" _id order:

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

Hate to burst your bubble, but that is just as how simple it is.

Point is that the "preceeding" bytes of an ObjectId actually come from the present "timestamp" value. Along with some other "randomness" in the overall content, this pretty much makes sure that the value as as whole is "monotonic" or "ever increasing" for its value.

like image 192
Neil Lunn Avatar answered Nov 15 '22 06:11

Neil Lunn