如何根据 MongoDB 中的另一个 collection 嵌入字段值更新嵌入 collection 字段的数组?

How to update array of embedded collection field based on another collection embedded field value in MongoDB?

我在这个论坛中搜索了我的以下问题,但找不到解决方案。

库存收集:

{
"_id" : ObjectId("555b1978af015394d1016374"),
"Billno" : "ABC1",
"Device_id" : "strsdedgfrtg12",
"item" : [ 
    {
        "item_id" : 232,
        "size" : "S",
        "qty" : 25
    }, 
    {
        "item_id" : 272,
        "size" : "M",
        "qty" : 5
    }
],
"category" : "clothing"

}

inventory_new collection:


{
"_id" : ObjectId("555b1978af015394d1016374"),
"Billno" : "ABC1",
"Device_id" : "strsdedgfrtg12",
"item" : [ 
    {
        "item_id" : 232,
        "size" : "S",
        "qty" : 25
    }, 
    {
        "item_id" : 272,
        "size" : "M",
        "qty" : 5000
    }
],
"category" : "clothing"

}

现在我必须用 inventory_new collections 嵌入项 "qty" 字段值更新库存 collection 嵌入数组的项 "qty" ..我试过下面的代码..但我没有成功。请指教

db.inventory.find().forEach(function (doc1) {
var doc2 = db.inventory_copy.find({ Billno: doc1.Billno},{ Device_id: doc1.Device_id},{ item.item_id: doc1.item.item_id}, {item.qty: 1 });
if (doc2 != null) {
    doc1.item.qty = doc2.item.qty;
    db.inventory.save(doc1);
}

});

谢谢

尝试以下更新:

db.inventory.find().forEach(function (doc1) {
    var doc2 = db.inventory_copy.findOne(
        { 
            "Billno": doc1.Billno, 
            "Device_id": doc1.Device_id,
            "item.item_id": doc1.item.item_id
        }
    );
    if (doc2 != null) { 
        doc1.item = doc2.item;    
        db.inventory.save(doc1);
    }
});