Jeffrey Kang
Jeffrey Kang

Reputation: 77

How can I get max value in nested documents?

I have a collection(named menucategories) in MongoDB 3.2.11:

{
    "_id" : ...
    "menus" : [
        {
            "code":0
        },
        {
            "code":1
        },
        {
            "code":2
        },
        {
            "code":3
        }
    ]
},
{
    "_id" : ...
    "menus" : [
        {
            "code":4
        },
        {
            "code":5
        },
        {
            "code":6
        },
        {
            "code":7
        }
    ]
},
{
    "_id" : ...
    "menus" : [
        {
            "code":8
        },
        {
            "code":9
        },
        {
            "code":10
        },
        {
            "code":11
        }
    ]
}

Every menucategory has array named menus. And every menu(element of the array) has code. The 'code' of menus is unique in every menu. I wanna get the maximum value of menu's code(in this case, 11). How can I achieve this?

Upvotes: 1

Views: 4044

Answers (3)

Kiran Sunkari
Kiran Sunkari

Reputation: 301

Try with aggregation:

db.collection.aggregate({ $group : { _id: 1, max: { $max: {$max : "$menus.code"}}}});

No need of any unwind, if you need find only maximum value.

Upvotes: 0

Sede
Sede

Reputation: 61225

You don't need to use the $unwind aggregation pipeline operator here because starting from MongoDB 3.2, some accumulator expressions are available in the $project stage.

db.collection.aggregate([
    {"$project": {"maxPerDoc": {"$max": "$menus.code"}}}, 
    {"$group": {"_id": null, "maxValue": {"$max": "$maxPerDoc"}}}
])

Responding a previous now deleted comment, you don't need to put your pipeline in an array so the following query will work as well.

db.collection.aggregate(
    {"$project": {"maxPerDoc": {"$max": "$menus.code"}}}, 
    {"$group": {"_id": null, "maxValue": {"$max": "$maxPerDoc"}}}
)

Upvotes: 1

Dhruv
Dhruv

Reputation: 173

If you want to find maximum value of code from all menus code then probable query will be as follows:

db.menucategories.aggregate([
  { $unwind: '$menus' },
  { $group: { _id: null, max: { $max: '$menus.code' } } },
  { $project: { max: 1, _id:0 } }
]) 

Click below links for more information regarding different operators:

$unwind, $group, $project

Upvotes: 3

Related Questions