How can I get max value in nested documents?

允我心安 提交于 2019-12-11 09:20:02

问题


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?


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/41327672/how-can-i-get-max-value-in-nested-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!