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

后端 未结 3 583
粉色の甜心
粉色の甜心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 20:32

    Try with db.collection.group

    For example, with this collection:

    > db.foo.find()
    { "_id" : ObjectId("..."), "a" : 1 }
    { "_id" : ObjectId("..."), "a" : 200 }
    { "_id" : ObjectId("..."), "a" : 230 }
    { "_id" : ObjectId("..."), "a" : -2230 }
    { "_id" : ObjectId("..."), "a" : 5230 }
    { "_id" : ObjectId("..."), "a" : 530 }
    { "_id" : ObjectId("..."), "a" : 1530 }
    

    You can use group using

    > db.foo.group({
        initial: { },
        reduce: function(doc, acc) {
            if(acc.hasOwnProperty('max')) {
                if(acc.max < doc.a)
                    acc.max = doc.a;
            } else {
                acc.max = doc.a
            }
          }
        })
    [ { "max" : 5230 } ]
    

    Since there is no key value in group all the objects are grouped in a single result

提交回复
热议问题