sql >> Base de Datos >  >> NoSQL >> MongoDB

¿Cómo actualizar un documento incrustado en una matriz anidada?

Según la descripción de su problema aquí:

For example I want to change the quantity of the item 10 in Invoice 123456789. Acabo de cambiar la Quantity a 3. Puede realizar cualquier operación aquí como desee. Solo necesita tomar nota de cómo usé arrayFilters aquí.

Pruebe esta consulta:

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

La consulta anterior se ejecutó con éxito desde Mongo Shell (Mongo 3.6.3). Y veo este resultado:

/* 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
            }
        ]
    }
 ]
}

¿Es eso lo que querías?