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

后端 未结 3 585
粉色の甜心
粉色の甜心 2021-01-02 20:04

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 th

3条回答
  •  Happy的楠姐
    2021-01-02 20:34

    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
    }
    

    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.

提交回复
热议问题