DevilCode
DevilCode

Reputation: 1100

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.

Upvotes: 6

Views: 6456

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

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.

Upvotes: 9

Related Questions