Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo does not have a max() function, how do I work around this?

Tags:

mongodb

I have a MongoDB collection and need to find the max() value of a certain field across all docs. This value is the timestamp and I need to find the latest doc by finding the largest timestamp. Sorting it and getting the first one gets inefficient really fast. Shall I just maintain a 'maxval' separately and update it whenever a doc arrives with a larger value for that field? Any better suggestions? Thanks much.

like image 331
Nitin Avatar asked Jun 12 '11 08:06

Nitin


People also ask

How much data MongoDB can handle?

The maximum size an individual document can be in MongoDB is 16MB with a nested depth of 100 levels. Edit: There is no max size for an individual MongoDB database.

Which of the following in MongoDB can limit the size of the result document for a query operation?

To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.

How many documents can a MongoDB collection have?

If you specify the maximum number of documents in a capped collection with create 's max parameter, the value must be less than 2 31 documents. If you do not specify a maximum number of documents when creating a capped collection, there is no limit on the number of documents.


1 Answers

if you have an index on the timestsamp field, finding the highest value is efficientl something like

db.things.find().sort({ts:-1}).limit(1)

but if having an index is too much overhead storing the max in a separate collection might be good.

like image 187
dm. Avatar answered Sep 28 '22 07:09

dm.