简体   繁体   中英

MongoDB update array of documents with new array of documents

It is possible to insert an array of objects, but not possible to update them. You have to remove them and then insert them. I don't want to have to remove and then insert them, because if the remove goes well but then the insert has an error, the data is lost. How can I update an array (all documents) in a collection, properly?

Inserting array of documents:

collection.insert(arrToInsert, function(err, results){
    console.log(results.ops);
});

Updating inserted array (not good):

collection.remove({}, function(err){
    collection.insert(arrUpdated, function(err, result) {
        console.log(results.ops);
    });
});

I have tried using collection.update but this does not allow an array.

edit: For example: Insert this array:

[
    {_id:0,name:"Harry"},
    {_id:1,name:"Jacob"},
    {_id:2,name:"Bob"}
]

and then, change it to this:

[
    {_id:0,name:"Dennis"},
    {_id:1,name:"Peter"},
    {_id:2,name:"Ghandi"}
]

My actual case is a bit more complicated, because the array has another key/value pair, and can be changed in many ways.

You mean .bulkWrite() , which allows multiple update operations ( Insert/Update/Remove) on the same collection in a single batch request. It actually is what modern drivers really call when either .insert() or .insertMany() is called with an array of documents.

Your new update would be:

var arrToUpdate = [
    {_id:0,name:"Dennis"},
    {_id:1,name:"Peter"},
    {_id:2,name:"Ghandi"}
];

collection.bulkWrite(
  arrToUpdate.map( d => ({
    "replaceOne": {
      "filter": { "_id": d._id },
      "replacement": d
    }
  })),
  function(err,result) {
    console.log(result)
  }
)

Where replaceOne is essentially an "update" without using any modifiers such as $set .

The point is that just like .insert() with an array or .insertMany() , the database receives only one request and response, but there are multiple operations in that request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM