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

后端 未结 3 569
粉色の甜心
粉色の甜心 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条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 20:50

    if you have an index on the timestsamp field, finding the highest value is efficientl something like

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

    but if having an index is too much overhead storing the max in a separate collection might be good.

提交回复
热议问题