Mongo doesn't have a max () function, how do I get around this?

I have a MongoDB collection and you need to find the max () value for a specific field in all documents. This value is a timestamp, and I need to find the last document by finding the largest timestamp. Sorting and getting the first one is inefficient very quickly. Should I just maintain "maxval" separately and update it whenever a document arrives with a large value for this field? Any best deals? Many thanks.

+6
source share
3 answers

Of course, if it will be a large collection, and if you always need to show the maximum time stamp, you may need to create a separate collection and store statistics there, rather than ordering a large collection each time.

statistic { _id = 1, id_from_time_stamp_collection = 'xxx', max_timestamp: value } 

And whenever a new doc arrives, just update the statistical collection with id = 1 (with the condition $ gt in the request, so if the new timestamp is greater than max_timestamp, then max_timestamp will be updated, otherwise not) .

In addition, you can store and update other statistics in the statistical collection.

+3
source

if you have an index in the timestsamp field, searching for the highest value is something like

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

but if there is too much overhead with the index, the maximum size in a separate collection may be good.

+18
source

Try with db.collection.group

For example, using this collection:

 > db.foo.find() { "_id" : ObjectId("..."), "a" : 1 } { "_id" : ObjectId("..."), "a" : 200 } { "_id" : ObjectId("..."), "a" : 230 } { "_id" : ObjectId("..."), "a" : -2230 } { "_id" : ObjectId("..."), "a" : 5230 } { "_id" : ObjectId("..."), "a" : 530 } { "_id" : ObjectId("..."), "a" : 1530 } 

You can use group using

 > db.foo.group({ initial: { }, reduce: function(doc, acc) { if(acc.hasOwnProperty('max')) { if(acc.max < doc.a) acc.max = doc.a; } else { acc.max = doc.a } } }) [ { "max" : 5230 } ] 

Since group does not have a key value, all objects are grouped into one result

-3
source

Source: https://habr.com/ru/post/890330/


All Articles