将嵌套值置于MongoDB的顶级

时间:2018-03-22 14:14:04

标签: mongodb

我想重塑一个MongoDB文件,如下所示: 这就是目前的情况:

{
"_id" : ObjectId("5a96d4a0af792cca1ec7d8cb"),
"Test" : "ABC",
"DATE" : "2018-02-28T16:04:55.00+01:00",
"Header" : "212735699",
"TraceIds" : [ 
    {
        "Id" : 1,
        "Names" : [ 
            {
                "LangCode" : "de",
                "CountryCode" : "DE",
                "Text" : "Komponente"
            }, 
            {
                "LangCode" : "en",
                "CountryCode" : "US",
                "Text" : "Component"
            }, 


        ],
        "Values" : [ 
            {
                "AId" : 1,
                "Names" : [ 
                    {
                        "LangCode" : "de",
                        "CountryCode" : "DE",
                        "Text" : "Teil"
                    }, 
                    {
                        "LangCode" : "en",
                        "CountryCode" : "US",
                        "Text" : "Part"
                    }, 

                ],
                "Value" : "1263000118"
            }, 

        ]
    }
],

现在我想提出价值1263000118并给它德语名称“Teil”。所有其他嵌入的值都应该消失。所以看起来应该是这样的:

{"_id" : ObjectId("5a96d4a0af792cca1ec7d8cb"),
"Test" : "ABC",
"DATE" : "2018-02-28T16:04:55.00+01:00",
"Header" : "212735699",
"Teil" : "1263000118",}

如果有人可以帮助我,那会很棒。感谢

1 个答案:

答案 0 :(得分:0)

使用聚合框架:

db.collection.aggregate([
    {$match: {
        _id: your_id,
        // Treatment to select which nested value you want
    }},
    {$project: {
        _id: "$_id",
        Test: "$Test",
        DATE: "$DATE",
        Header: "$Header",
        Teil: "$Values.$.Value
    }}
]);

这样的事情应该有效