sql >> Databasteknik >  >> NoSQL >> MongoDB

Mongoose multi-uppdatering

Om du antar att du hade en rad objekt som du ville uppdatera i din samling på matchande ID som

var soldItems = [
        {
            "_id": 1,
            "value": 4
        },
        {
            "_id": 2,
            "value": 27
        }
    ];

då kan du använda code>forEach() metod på arrayen för att iterera den och uppdatera din samling:

soldItems.forEach(function(item)){
    Model.update({"_id": item._id}, {"$set": {"value": item.value }}, callback);
});

eller använd löften som

var updates = [];
soldItems.forEach(function(item)){
    var updatePromise = Model.update({"_id": item._id}, {"$set": {"value": item.value }});
    updates.push(updatePromise);
});

Promise.all(updates).then(function(results){
    console.log(results);
});

eller med karta ()

var updates = soldItems.map(function(item)){
    return Model.update({"_id": item._id}, {"$set": {"value": item.value }});       
});

Promise.all(updates).then(function(results){
    console.log(results);
}); 

För större arrayer kan du dra fördel av att använda ett bulk-skriv-API för bättre prestanda. För Mongoose-versioner >=4.3.0 som stöder MongoDB Server 3.2.x ,du kan använda bulkWrite() för uppdateringar. Följande exempel visar hur du kan gå tillväga:

var bulkUpdateCallback = function(err, r){
    console.log(r.matchedCount);
    console.log(r.modifiedCount);
}
// Initialise the bulk operations array
var bulkOps = soldItems.map(function (item) { 
    return { 
        "updateOne": { 
            "filter": { "_id": item._id } ,              
            "update": { "$set": { "value": item.value } } 
        }         
    }    
});

// Get the underlying collection via the native node.js driver collection object
Model.collection.bulkWrite(bulkOps, { "ordered": true, w: 1 }, bulkUpdateCallback);

För Mongoose-versioner ~3.8.8, ~3.8.22, 4.x som stöder MongoDB Server >=2.6.x , kan du använda Bulk API enligt följande

var bulk = Model.collection.initializeOrderedBulkOp(),
    counter = 0;

soldItems.forEach(function(item) {
    bulk.find({ "_id": item._id }).updateOne({ 
        "$set": { "value": item.value }
    });

    counter++;
    if (counter % 500 == 0) {
        bulk.execute(function(err, r) {
           // do something with the result
           bulk = Model.collection.initializeOrderedBulkOp();
           counter = 0;
        });
    }
});

// Catch any docs in the queue under or over the 500's
if (counter > 0) {
    bulk.execute(function(err,result) {
       // do something with the result here
    });
}


  1. Hur använder man tredje parts bibliotek i glasfisk?

  2. Sortera underfält med okänd förälder

  3. Hantera att skicka två parametrar i ett API-anrop i Angular App

  4. PHP-start Kan inte ladda det dynamiska biblioteket php_mongo.dll