2

I'm trying to get the highest value of a child value. If I have two documents like this

{
    "_id" : ObjectId("5585b8359557d21f44e1d857"),
    "test" : {
        "number" : 1,
        "number2" : 1
    }
}

{
    "_id" : ObjectId("5585b8569557d21f44e1d858"),
    "test" : {
        "number" : 2,
        "number2" : 1
    }
}

How would I get the highest value of key "number"?

XLordalX
  • 584
  • 1
  • 7
  • 25
  • Very similar to http://stackoverflow.com/questions/4762980/getting-the-highest-value-of-a-column-in-mongodb . I think it's not duplicate just because that you want to get the child max value and not the max of a single column. – Dinei Jun 20 '15 at 19:20

3 Answers3

2

Using dot notation:

db.testSOF.find().sort({'test.number': -1}).limit(1)
TechWisdom
  • 3,960
  • 4
  • 33
  • 40
1

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.

db.collection.find("_id" => x).sort({"test.number" => -1}).limit(1).first()

quoted from: Getting the highest value of a column in MongoDB

Community
  • 1
  • 1
connexo
  • 53,704
  • 14
  • 91
  • 128
1

To get the highest value of the key "number" you could use two approaches here. You could use the aggregation framework where the pipeline would look like this

db.collection.aggregate([
    {
        "$group": {
            "_id": 0,
            "max_number": {
                "$max": "$test.number"
            }
        }
    }
]) 

Result:

/* 0 */
{
    "result" : [ 
        {
            "_id" : 0,
            "max_number" : 2
        }
    ],
    "ok" : 1
}

or you could use the find() cursor as follows

db.collection.find().sort({"test.number": -1}).limit(1)
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 1
    @XLordalX Yes. You can see the AsyaKamsky's answer here: http://stackoverflow.com/a/22122161/3136474 – Dinei Jun 20 '15 at 19:19
  • Thanks @DineiA.Rockenbach for the reference, great answer with some good explanations. – chridam Jun 20 '15 at 19:21