Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the max value of a field in MongoDB

Tags:

mongodb

like:

{id:4563214321,updateTime:long("124354354")}

there are always new collections enter the db, so I would like to always get latest updated documents aka the largest update time. how to design the shell script? thanks in advance.

like image 498
Mogician Ha Avatar asked Oct 15 '25 17:10

Mogician Ha


1 Answers

You can use a combination of limit and sort to achieve this goal.

db.collectionName.find({}).sort({"updateTime" : -1}).limit(1)

This will sort all of your fields based on update time and then only return the one largest value.

I would recommend adding an index to this field to improve performance.

like image 158
Hughzi Avatar answered Oct 17 '25 12:10

Hughzi