Getting the highest value of a column in MongoDB

后端 未结 9 1607
粉色の甜心
粉色の甜心 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:07

    It will work as per your requirement.

    transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first()
    
    0 讨论(0)
  • 2020-12-05 03:12

    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()
    
    0 讨论(0)
  • 2020-12-05 03:18
    db.collectionName.aggregate(
      {
        $group : 
        {
          _id  : "",
          last : 
          {
            $max : "$sellprice"
          }
        }
      }
    )
    
    0 讨论(0)
  • 2020-12-05 03:20

    Example mongodb shell code for computing aggregates.

    see mongodb manual entry for group (many applications) :: http://docs.mongodb.org/manual/reference/aggregation/group/#stage._S_group

    In the below, replace the $vars with your collection key and target variable.

    db.activity.aggregate( 
      { $group : {
          _id:"$your_collection_key", 
          min: {$min : "$your_target_variable"}, 
          max: {$max : "$your_target_variable"}
        }
      } 
    )
    
    0 讨论(0)
  • 2020-12-05 03:21

    Use aggregate():

    db.transactions.aggregate([
      {$match: {id: x}},
      {$sort: {sellprice:-1}},
      {$limit: 1},
      {$project: {sellprice: 1}}
    ]);
    
    0 讨论(0)
  • 2020-12-05 03:25

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

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