如何更新嵌入文档到嵌套数组?(How to update an embedded document

2019-10-30 02:58发布

我有这种结构为蒙戈集合:

{
  "_id": "12345678",
  "Invoices": [
    {
      "_id": "123456789",
      "Currency": "EUR",
      "DueTotalAmountInvoice": 768.3699999999999,
      "InvoiceDate": "2016-01-01 00:00:00.000",
      "Items": [
        {
          "Item": 10,
          "ProductCode": "ABC567",
          "Quantity": 1
        },
        {
          "Item": 20,
          "ProductCode": "CDE987",
          "Quantity": 1
        }
      ]
    },
    {
      "_id": "87654321",
      "Currency": "EUR",
      "DueTotalAmountInvoice": 768.3699999999999,
      "InvoiceDate": "2016-01-01 00:00:00.000",
      "Items": [
        {
          "Item": 30,
          "ProductCode": "PLO987",
          "Quantity": 1,
          "Units": "KM3"
        },
        {
          "Item": 40,
          "ProductCode": "PLS567",
          "Quantity": 1,
          "DueTotalAmountInvoice": 768.3699999999999
        }
      ]
    }
  ]
}

所以我有一个第一对象存储几张发票和每个发票存储几个项目。 一个项目是嵌入文档。 因此,在关系modelisation:一位顾客有1个或几个发票的发票有1个或几个项目

我面临的一个问题,因为我想更新特定项目到特定特定发票。 例如,我想改变项目10的数量在发票123456789。

这怎么可能做到这一点在MongoDB中?

我试过了 :

  • 按声明,但它似乎并没有为嵌套数组工作

  • arrayFilters它似乎却并没有在嵌套阵列(只有简单的数值数组)嵌入文档工作。

你能给我一些关于它的建议吗?

谢谢 !

Answer 1:

根据你的问题的描述在这里:

For example I want to change the quantity of the item 10 in Invoice 123456789.我只是改变了Quantity为3,只要你想你可以在这里进行任何操作。 你只需要注意一下我是如何用arrayFilters这里。

试试这个查询:

db.collection.update(
 {"_id" : "12345678"},
 {$set:{"Invoices.$[element1].Items.$[element2].Quantity":3}},
 {multi:true, arrayFilters:[ {"element1._id": "123456789"},{ 
  "element2.Item": { $eq: 10 }} ]}
)

上述查询从蒙戈壳(蒙戈3.6.3)成功执行。 我看到这样的结果:

/* 1 */
{
"_id" : "12345678",
"Invoices" : [ 
    {
        "_id" : "123456789",
        "Currency" : "EUR",
        "DueTotalAmountInvoice" : 768.37,
        "InvoiceDate" : "2016-01-01 00:00:00.000",
        "Items" : [ 
            {
                "Item" : 10,
                "ProductCode" : "ABC567",
                "Quantity" : 3.0
            }, 
            {
                "Item" : 20,
                "ProductCode" : "CDE987",
                "Quantity" : 1
            }
        ]
    }, 
    {
        "_id" : "87654321",
        "Currency" : "EUR",
        "DueTotalAmountInvoice" : 768.37,
        "InvoiceDate" : "2016-01-01 00:00:00.000",
        "Items" : [ 
            {
                "Item" : 30,
                "ProductCode" : "PLO987",
                "Quantity" : 1,
                "Units" : "KM3"
            }, 
            {
                "Item" : 40,
                "ProductCode" : "PLS567",
                "Quantity" : 1,
                "DueTotalAmountInvoice" : 768.37
            }
        ]
    }
 ]
}

这是你想要的吗?



文章来源: How to update an embedded document into a nested array?