I am using Ruby on Rails and I have the following Mongo collection,
{
_id: 1,
name: "Jackie Chan",
sn: "ABC123",
Country: Australia
},
{
_id: 2,
name: "Brad Pitt",
sn: "ABC124",
Country: Russia
},
{
_id: 3,
name: "Al Pacino",
sn: "ABC125",
Country: USA
}
I have another MYSQL table called Device
, which also has Country and device_sn
field. I want to find the MondoDB document using device_sn
and update the value of mongoDB country
field from Device
table. I want to update the country field of each document to a different values received from another MYSQL table.
[#<Device:0x00007f9adb7df898 device_sn: "ABC123", country: "US">,
#<Device:0x00007f9adb7df668 device_sn: "ABC124", country: "CA">,
#<Device:0x00007f9adb7df370 device_sn: "ABC125", country: "AU">]
I know how to update the multiple document with the same value, but here the case is each document should be updated with different values of country
field. I know how to perform it using looping and updating, but I want to know is there a bulk update or updateMany query available to perform this type of operation.
2
Answers
There is no way to perform that otherwise than by using looping.
You can use mongodb bulkwrite method. This method takes array of write operations. This is much better then simply looping the data and updating the database. As it will reduce your network calls drastically.
In your case you have to create multiple objects of updateOne or updateMany by iterating your data. Please refer to this documentation of mongodb to know more.
Ruby mongo driver implementation for same.