I am trying to retrieve one element from a mongo collection, the one with the greatest _id field. I know this can be done by querying:
db.collection.find().sort({_id: -1}).limit(1)
But it kind of seems unelegant and I was wondering whether there is a way to get that specific element using findOne()
Note: I want to do this because, from what I've read in ObjectId, the first bytes correspond to the miliseconds since the Epoch and thus, the last element being inserted will have the greatest _id. Is there any other way to retrieve the last element inserted in a collection?
ObjectId
is usually created by the client driver, so it's only as accurate/reliable as the clients being used. If two drivers insert at the same second, the results won't be predictable. – WiredPrairie