how to get the max value of a field in MongoDB

依然范特西╮ 提交于 2021-02-05 06:10:22

问题


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.


回答1:


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.




回答2:


This is a repeated question, you can find an answer in this link Using findOne in mongodb to get element with max id

use like this,

db.collection.find().sort({updateTime:-1}).limit(1).pretty()

as findOne you can do it with this syntax:

db.collection.findOne({$query:{},$orderby:{_updateTime:-1}})



来源:https://stackoverflow.com/questions/35984389/how-to-get-the-max-value-of-a-field-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!