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

¿Cómo cambiar todos los elementos de la matriz en un documento mongodb a un valor determinado?

La mejor manera de hacer esto es hacer coincidir el elemento de la matriz y actualizarlo individualmente con el $ posicional operador usando el Bulk() API. Realmente no deberías gastar tu qty matriz.

var bulk = db.mycollection.initializeOrderedBulkOp(),   
    count = 0;

db.mycollection.find({ "code" : "efg" }).forEach(function(doc){ 
    var qty = doc["qty"]; 
    for (var idx = 0; idx < qty.length; idx++){ 
        bulk.find({ 
            "_id": doc._id, 
            "qty": { "$elemMatch": { "num": qty[idx]["num"]}}
        }).update({ "$set": { "qty.$.num": 0 }})
    }     
    count++;  
    if (count % 200 == 0) { 
        // Execute per 200 operations and re-init.
        bulk.execute(); 
        bulk = db.mycollection.initializeOrderedBulkOp(); 
    } 
})

// Clean up queues
if (count % 200 != 0)
    bulk.execute();