简体   繁体   English

MongoDB使用新的文档数组更新文档数组

[英]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. 我尝试使用collection.update,但这不允许使用数组。

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. 您的意思是.bulkWrite() ,它允许在单个批处理请求中对同一集合进行多个更新操作(插入/更新/删除)。 It actually is what modern drivers really call when either .insert() or .insertMany() is called with an array of documents. 实际上,当使用文档数组调用.insert().insertMany()时,现代驱动程序实际上会调用它们。

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 . 其中replaceOne本质上是一个“更新”,而不使用任何修饰符,例如$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. 关键是,就像具有数组或.insertMany() .insert()一样,数据库仅接收一个请求和响应,但是该请求中有多个操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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