繁体   English   中英

使用MongoDB投影数组元素

[英]Projection of array elements using MongoDB

我有以下json文件:

{
    "Section": {
        "Name": "Section 1",
        "Description": "Section 1 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Firstname",
        "Desc": "Users first name",
        "Type": "Text"
    }, {
        "Name": "Lastname",
        "Desc": "Users last name",
        "Type": "Text"
    }]
} {
    "Section": {
        "Name": "Section 2",
        "Description": "Section 2 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Section 2 Item",
        "Desc": "Section 2 Desc",
        "Type": "Text"
    }]
}

我想问一下是否有任何方法可以基于Data.Name投影项目。 就像在['Firstname','Section 2 Item']]中使用Data.Name投影所有项目一样,包括Section对象。 因此结果应为:

{
    "Section": {
        "Name": "Section 1",
        "Description": "Section 1 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Firstname",
        "Desc": "Users first name",
        "Type": "Text"
    }]
} {
    "Section": {
        "Name": "Section 2",
        "Description": "Section 2 information",
        "Icon": "test.png"
    },
    "Data": [{
        "Name": "Section 2 Item",
        "Desc": "Section 2 Desc",
        "Type": "Text"
    }]
}

不知道这是否可能。

提前致谢。

您可以使用$位置投影运算符来执行此操作,该运算符标识查询对象中匹配的数组元素的索引:

db.test.find(
    {'Data.Name': {$in: ["Firstname", "Section 2 Item"]}}, 
    {Section: 1, 'Data.$': 1})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM