Mongo没有max()函数,该如何解决? [英] Mongo does not have a max() function, how do I work around this?

查看:84
本文介绍了Mongo没有max()函数,该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MongoDB集合,需要在所有文档中查找某个字段的max()值.这个值是时间戳,我需要通过找到最大的时间戳来找到最新的文档.对其进行排序并获得第一个将很快变得效率低下.我是否应该单独维护一个"maxval"并在文档到达该字段的值较大时对其进行更新?还有更好的建议吗? 非常感谢.

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.

推荐答案

要确定它是否将是大集合,并且如果您始终需要显示最大时间戳,则可能需要创建单独的集合并在其中存储统计数据,而不是分别订购大集合时间.

For sure if it will be big collection and if you need always display max timestamp you may need create separate collection and store statistic data there instead of order big collection each time.

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

每当新文档到来时,只需更新id = 1(在查询中带有$ gt条件)的统计信息收集,因此,如果新时间戳大于max_timestamp,则max_timestamp将被更新,否则-否).

And whenever new doc come just update statistic collection with id = 1(with $gt condition in query, so if new timestamp will be greater than max_timestamp then max_timestamp will be updated, otherwise - no).

也许您还可以在统计信息收集中存储和更新其他统计数据.

Also probably you can store and update other statistic data within statistic collection.

这篇关于Mongo没有max()函数,该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆