如何在嵌套文档中获得最大价值? [英] How can I get max value in nested documents?

查看:64
本文介绍了如何在嵌套文档中获得最大价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB 3.2.11中有一个集合(名为 menuategories ):

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
        }
    ]
}

每个菜单都有一个名为 menus 的数组.并且每个菜单(数组的元素)都有代码.菜单的"代码"在每个菜单中都是唯一的.我想获取菜单代码的最大值(在本例中为 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?

推荐答案

如果要从所有菜单代码中查找代码的最大值,则可能的查询如下:

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 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆