Reputation: 31
I Need to update the JSON value in MongoDB.
{
INR: 71.7406004869,
BRL: 4.1883509152,
RUB: 63.6918221982,
HRK: 6.7076909206,
TRY: 5.6890271391,
CNY: 7.0266883058,
NOK: 9.1081056713,
NZD: 1.5543233252,
ZAR: 14.6645929132,
USD: 1,
MXN: 19.4436029213,
}
My-schema :
{
id : 1
name: US Dollar
code:USD
rate:1
},
{
id : 2
name: Indian rupees
code:INR
rate: 70.018
}
How to update multiple documents in the collections where I need to check the 'code' field and then update 'rate' field.
Upvotes: 0
Views: 160
Reputation: 3529
Since assuming you are using mongoose
as the ODM, to update multiple documents from the object Moldel.bulkWrite()
api can be used to have a single round trip to db and update the corresponding documents.
const rateData = {
INR: 71.7406004869,
BRL: 4.1883509152,
RUB: 63.6918221982,
HRK: 6.7076909206,
TRY: 5.6890271391,
CNY: 7.0266883058,
NOK: 9.1081056713,
NZD: 1.5543233252,
ZAR: 14.6645929132,
USD: 1,
MXN: 19.4436029213
};
let bulkOps = [];
Object.keys(rateData).forEach((k, index) => {
bulkOps.push({
updateOne: {
filter: { code: k },
update: { $set: {rate: rateData[k]} }
}
});
});
//Model.bulkWrite returns a promise allows using (then, catch)
Model.bulkWrite(bulkOps)
.then(result => {
console.info("Bulk update information::", result);
})
.catch(e => {
console.error("Error at bulk update::", e);
});
Upvotes: 1