XLordalX
XLordalX

Reputation: 594

MongoDB - Get highest value of child

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"?

Upvotes: 2

Views: 500

Answers (3)

connexo
connexo

Reputation: 56783

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

Upvotes: 1

chridam
chridam

Reputation: 103445

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)

Upvotes: 1

TechWisdom
TechWisdom

Reputation: 4315

Using dot notation:

db.testSOF.find().sort({'test.number': -1}).limit(1)

Upvotes: 2

Related Questions