MongoDB,选择嵌套数组字段

时间:2015-09-22 15:03:25

标签: mongodb mongodb-query aggregation-framework

我有一个集合,文件有嵌套数组,我想只选择较低的数组,是否可能?

我试过这个,但它不起作用:

db.collection.find({},{'family.children.$.toys' :1})

文档示例

   {
    "id":1000,
    "name": "Bob",
    "surname":"The Builder",
    "family":{
        "size":2,
        "status": "happy",
        "children":[{
            "name":"Jim",
            "school": "St. Mary",
            "toys":[{
                "name":"Lego"
            },
            {
                "name":"Playstation"
            }]
        },
        {
            "name":"Kate",
            "school": "St. Mary",
            "toys":[{
                "name":"Xbox"
            },
            {
                "name":"Barbie"
            }]
        }
        ]
    }
}

预期结果(仅提取玩具清单):

{
_id:1000,
family:{
    childrens:[{
        toys:[{
            name:Lego
        },
        {
            name:Playstation
        }]
    },
    {
        toys:[{
            name:Xbox,
        },
        {
            name:Barbie
        }]
    }
    ]
}}

2 个答案:

答案 0 :(得分:4)

if (Convert.ToInt32(Session["Level"]) >= 2)
        {
            MenuItem mi2 = new MenuItem("MenuItem2", "SchoolView.aspx");
            mi2.ToolTip = "tool tip";
            mi2.Selectable = true;
            bootMenu.Items[0].ChildItems.Add(mi2);
        }

示例输出:

    <asp:Menu ID="bootMenu" 
    runat="server" 
    Orientation="Vertical" 
    StaticDisplayLevels="1"
    StaticEnableDefaultPopOutImage="False"
    OnMenuItemClick="BootMenu_MenuItemClick" 
    MaximumDynamicDisplayLevels="10" 
    EnableViewState="false"
    CssClass="nav navbar-fix-top" 
    DynamicMenuStyle-CssClass="dropdown-menu" 
    IncludeStyleBlock="false" 
    SkipLinkText=""
    RenderingMode="List">

答案 1 :(得分:1)

您也可以通过聚合执行此操作。您使用$map运算符仅返回toys字段。

db.collection.aggregate([{ 
    "$project": { 
        "family.childrens": { 
            "$map": { 
                "input": "$family.children",
                "as": "f", 
                "in": { "toys": "$$f.toys" }
            }
        }
     }}
 ])