George
George

Reputation: 2422

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.

Upvotes: 0

Views: 552

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

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.

Upvotes: 1

Related Questions