Getting the highest value of a column in MongoDB

2019-01-21 22:27发布

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 do it.

I tried the following (and different combinations):

transactions.find("id" => x).max({"sellprice" => 0})

But it keeps throwing errors. What's a good way to do it besides sorting and getting the top/bottom?

Thank you!

9条回答
Juvenile、少年°
2楼-- · 2019-01-21 23:01

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.)

查看更多
Animai°情兽
3楼-- · 2019-01-21 23:03

max() does not work the way you would expect it to in SQL for Mongo. This is perhaps going to change in future versions but as of now, max,min are to be used with indexed keys primarily internally for sharding.

see http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers

Unfortunately for now the only way to get the max value is to sort the collection desc on that value and take the first.

transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first()
查看更多
一夜七次
4楼-- · 2019-01-21 23:03

It will work as per your requirement.

transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first()
查看更多
唯我独甜
5楼-- · 2019-01-21 23:12

Use aggregate():

db.transactions.aggregate([
  {$match: {id: x}},
  {$sort: {sellprice:-1}},
  {$limit: 1},
  {$project: {sellprice: 1}}
]);
查看更多
等我变得足够好
6楼-- · 2019-01-21 23:13

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

查看更多
爷的心禁止访问
7楼-- · 2019-01-21 23:16

Following query does the same thing: db.student.find({}, {'_id':1}).sort({_id:-1}).limit(1)

For me, this produced following result: { "_id" : NumberLong(10934) }

查看更多
登录 后发表回答