1

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?

styvane
  • 59,869
  • 19
  • 150
  • 156
Jeffrey Kang
  • 77
  • 1
  • 8
  • Possible duplicate of [mongodb how to get max value from collections](http://stackoverflow.com/questions/32076382/mongodb-how-to-get-max-value-from-collections) – Smita Ahinave Dec 26 '16 at 07:28
  • @SmitaAhinave this is not a valid duplicate. Op specifically mentioned that they are on MongoDB 3.2 – styvane Dec 26 '16 at 10:32

3 Answers3

3

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

Dhruv
  • 173
  • 11
  • Your comment on @ShaishabRoy's now deleted answer is wrong. You don't always need to put your pipeline in an array. Also note that OP is using MongoDB 3.2 which means that your answer here is only *factually* correct. – styvane Dec 26 '16 at 10:41
1

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"}}}
)
styvane
  • 59,869
  • 19
  • 150
  • 156
0

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.

Gustavo Morales
  • 2,614
  • 9
  • 29
  • 37
Kiran Sunkari
  • 301
  • 1
  • 3
  • 15