简体   繁体   中英

How to update multiple documents?

I want to update multiple documents.
My current Document,
Document Account

{
    "_id" : "5cbd96aca1a6363473d4g8745",
    "contact" : [
         "5cbd96aca1a6363473d4a968",
    ]
},
{
    "_id" : "5cbd96aca1a6363473d4g8746",
    "contact" : [             
         "5cbd96aca1a6363473d4z7632",
    ]
}

I need below output,
update contact array with different _id .
Document Account

{
    "_id" : "5cbd96aca1a6363473d4g8745",
    "contact" : [
         "5c98833f98770728a7047f1a",
         "5cbd96aca1a6363473d4a968",
    ]
},
{
    "_id" : "5cbd96aca1a6363473d4g8746",
    "contact" : [     
         "5caddf78b8c0645402090536",        
         "5cbd96aca1a6363473d4z763",
    ]
}

使用$addToSet$push通过bulk update推送ID。

You can use update with upsert. It will update the doc if exist and if not then it will create new one. for example:

//Make a obj to set
var contacts = {
  id: req.body.id,
  contactIds: req.body.contactIds,
};

req.app.db.models.ModelsName.update(
{
//if you want multiple fields to be update
  $and: [{ id: contacts.id }, { contactIds: { $in: contacts.contactIds } }]
},

//Set the above obj 
{ $set: contacts },
{ upsert: true },
(err, result) => {
  if (err) {
    console.log(err.message)
  }
  console.log("Updated successfully")
})

This is just a reference. Modify accordingly your use.

You can use Bulk.find.update() method to update all matching documents. example: var bulk = db.items.initializeUnorderedBulkOp(); bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } ); bulk.find( { item: null } ).update( { $set: { item: "TBD" } } ); bulk.execute(); var bulk = db.items.initializeUnorderedBulkOp(); bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } ); bulk.find( { item: null } ).update( { $set: { item: "TBD" } } ); bulk.execute();

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