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?
MongoDB findOne() method returns only one document that satisfies the criteria entered. If the criteria entered matches for more than one document, the method returns only one document according to natural ordering, which reflects the order in which the documents are stored in the database.
findOne() Finds a single document from a collection or view. If multiple documents match the query, this returns the first matching document according to the query's sort order or natural order.
Step 2.1 - We will group employee by firstName and find maximum salary of each group. Step 2.2- We will use aggregate() method, $group operator and $max operator. Step 4.3 - Then we will group employee by firstName and find maximum salary of each group. Step 4.4 - We will use aggregate() method, $group operator.
You should use find
, like you already are, and not aggregation which will be slower since it needs to scan all the values of _id fields to figure out the max.
As comments pointed out there is no difference between using find() and findOne() - functionally or elegance-wise. In fact, findOne
in the shell (and in the drivers which implement it) is defined in terms of find (with limit -1 and with pretty print in the shell).
If you really want to do the equivalent of
db.collection.find().sort({_id:-1}).limit(1).pretty()
as findOne
you can do it with this syntax:
db.collection.findOne({$query:{},$orderby:{_id:-1}})
You can get max _id using aggregation of mongodb. Find and sort may overkill's.
db.myCollection.aggregate({ $group: { _id: '', last: { $max: "$_id" } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With