Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using findOne in mongodb to get element with max id

Tags:

mongodb

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?

like image 963
Jorge Avatar asked Mar 01 '14 18:03

Jorge


People also ask

How does findOne work in MongoDB?

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.

What does findOne return MongoDB?

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.

How does MongoDB calculate max salary?

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.


2 Answers

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}}) 
like image 68
Asya Kamsky Avatar answered Oct 18 '22 17:10

Asya Kamsky


You can get max _id using aggregation of mongodb. Find and sort may overkill's.

db.myCollection.aggregate({     $group: {         _id: '',         last: {             $max: "$_id"         }     } }); 
like image 41
Sumeet Kumar Yadav Avatar answered Oct 18 '22 17:10

Sumeet Kumar Yadav