Manoj Ghediya
Manoj Ghediya

Reputation: 597

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",
    ]
}

Upvotes: 1

Views: 139

Answers (3)

Sumit Yadav
Sumit Yadav

Reputation: 44

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.

Upvotes: 2

Abhishek Mani
Abhishek Mani

Reputation: 522

Use $addToSet or $push to push id with bulk update.

Upvotes: 2

Ravikiran Gambhire
Ravikiran Gambhire

Reputation: 91

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();

Upvotes: 0

Related Questions