簡體   English   中英

如何基於MongoDB中的另一個集合嵌入字段值更新嵌入集合字段的數組?

[英]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"

}

庫存_新收藏:


{
"_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"

}

現在,我要用庫存_新集合嵌入式項目“ qty”字段值更新庫存集合嵌入式數組的項目“ 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);
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM