Getting the highest value of a column in MongoDB

后端 未结 9 1608
粉色の甜心
粉色の甜心 2020-12-05 02:44

I\'ve been for some help on getting the highest value on a column for a mongo document. I can sort it and get the top/bottom, but I\'m pretty sure there is a better way to d

相关标签:
9条回答
  • 2020-12-05 03:29

    Sorting might be overkill. You can just do a group by

    db.messages.group(
               {key: { created_at:true },
                cond: { active:1 },
                reduce: function(obj,prev) { if(prev.cmax<obj.created_at) prev.cmax = obj.created_at; },
                initial: { cmax: **any one value** }
                });
    
    0 讨论(0)
  • 2020-12-05 03:29

    If the column's indexed then a sort should be OK, assuming Mongo just uses the index to get an ordered collection. Otherwise it's more efficient to iterate over the collection, keeping note of the largest value seen. e.g.

    max = nil
    coll.find("id" => x).each do |doc| 
        if max == nil or doc['sellprice'] > max then
            max = doc['sellprice'] 
        end
    end
    

    (Apologies if my Ruby's a bit ropey, I haven't used it for a long time - but the general approach should be clear from the code.)

    0 讨论(0)
  • 2020-12-05 03:34

    Assuming I was using the Ruby driver (I saw a mongodb-ruby tag on the bottom), I'd do something like the following if I wanted to get the maximum _id (assuming my _id is sortable). In my implementation, my _id was an integer.

    result = my_collection.find({}, :sort => ['_id', :desc]).limit(1)
    

    To get the minimum _id in the collection, just change :desc to :asc

    0 讨论(0)
提交回复
热议问题