簡體   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