I have got a Order document with below structure,
"order" : {
"id": 999,
"products" : [
{
"id": 1,
"price": 12.344746
},
{
"id": 2,
"price": 45.688755
},
{
"id": 3,
"price": 89.5667574
}
],
"total": 151.7965567
}
I'm writing a script to fix the decimal places of the price field using toFixed(). In order to update all the products I am looping products and calling update() on each product id.
order.products.forEach((product) => {
var updatedPrice = product.price.toFixed(2);
db.orders.updateOne({
id: 999,
products: {
$elemMatch: {
id: product.id
}
}
}, {
$set: {
"products.$.price": updatedPrice
}
})
})
var updatedTotal = order.total.toFixed(2);
db.orders.updateOne({
id: 999
},
{
$set: {
total: updatedTotal
}
})
So, in order to update one record I am doing 4 separate update operations.
Is it possible to update everything in a single operation?
P.S: Apart from products and total there are many other fields. I have used only two for simplicity. Also I do not wish to set each field.