MongoDB查询-子文档

时间:2019-12-09 12:46:31

标签: mongodb aggregation-framework

我下面有一个这样的文件

{ 
    "_id" : ObjectId("xxxx"), 
    "main_array" : [
        {
            "cars" : [
                "BMW", 
                "Toyota"
            ], 
            "parts" : [
                990
            ]
        }
    ]
}
{ 
    "_id" : ObjectId("yyy"), 
    "main_array" : [
        {
            "cars" : [
                "C2", 
                "BMW"
            ], 
            "parts" : [
                991, 
                123
            ]
        }, 
        {
            "cars" : [
                "Audi", 
                "Ford"
            ], 
            "parts" : [
                990
            ]
        }
    ]
}

部分-1 我需要查询零件:990,并且仅返回与相同零件相同的汽车阵列文档-> 990

输出

 "cars" : [
                "Audi", 
                "Ford"
            ]

第2部分- 更新所有其他具有相同零件编号的文件

{ 
    "_id" : ObjectId("xxxx"), 
    "main_array" : [
        {
            "cars" : [
                "BMW", 
                "Toyota"
            ], 
            "parts" : [
                990
            ],
            "other_cars" : [[
                "Audi", 
                "Ford"
            ]]
        }
    ]
}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

第1部分:

db.collection.aggregate([
    {
        $match: {
            "main_array.parts": 990,
            "_id": {$ne: ObjectId("xxxx")} //exclude curr document
        }
    },
    {
        $unwind: "$main_array"
    },
    {
        $match: {
            "main_array.parts": 990
        }
    },
    {
        $unwind: "$main_array.cars"
    },
    {
        $group: {
            _id: null,
            cars: {$addToSet: "$main_array.cars"}
        }
    },
    {
        $project: {
            _id: 0,
            cars: 1
        }
    }
])

第2部分: 现在我们只需要更新旧文档:

db.collection.findOneAndUpdate(
   { _id: oldDocumentID },               
   { $set: { "main_array.$[element].other_cars" : aggregationResultsArray } },
   {
       arrayFilters: [ { "element.parts": 990 } ]
   }
)