Akaash
Akaash

Reputation: 75

Can I update different documents in a single query in MongoDB?

I want to update different documents in MongoDB with just a single query. My existing Database collection looks like:

[ { "_id":"1", "name": null, "Age": null }, { "_id":"2", "name":null, "Age":null}, { "_id":"3", "name":null, "Age": null } ]

I have the following JSON:

[ { "_id":"1", "name":"Arav", "Age":"25" }, { "_id":"2", "name":"Mohan", "Age":"64" }, { "_id":"3", "name":"Nishant", "Age":"23" } ]

I want to know if its possible to update all the existing 3 documents with the respective data from above JSON with a single query. Something like:

db.products.insert( [ { "_id":"1", "name":"Arav", "Age":"25" }, { "_id":"2", "name":"Mohan", "Age":"64" }, { "_id":"3", "name":"Nishant", "Age":"23" } ] )

The problem is that it returns duplicate error and doesn't update the document if already existing.

Upvotes: 2

Views: 97

Answers (2)

Vishakha Gupta
Vishakha Gupta

Reputation: 1

It is possible to insert 3 or more documents using one single query using insertMany instead of just insert as shown below -

db.products.insertMany( [ { "_id":"1", "name":"Arav", "Age":"25" }, { "_id":"2", "name":"Mohan", "Age":"64" }, { "_id":"3", "name":"Nishant", "Age":"23" } ] ).

insertMany returns a document containing:
- A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.
- An array of _id for each successfully inserted documents id

Upvotes: 0

Ashh
Ashh

Reputation: 46441

You can use bulkWrite operation

Suppose you have this JSON needs to be updated

const array = [
  {
    "_id": "1",
    "name": "Arav",
    "Age": "25"
  },
  {
    "_id": "2",
    "name": "Mohan",
    "Age": "64"
  },
  {
    "_id": "3",
    "name": "Nishant",
    "Age": "23"
  }
]

Now with the bulkWrite query

Model.bulkWrite(
  array.map((data) => 
    ({
      updateOne: {
        filter: { _id: data._id },
        update: { $set: { name: data.name, Age: data.age } }
      }
    })
  )
})

Upvotes: 2

Related Questions