Prior to Mongo version 4.2 you have to execute each update separately as they have different conditions, this is best done using bulkWrite in order to save up on network overhead, like so:
const input = [
{_id: ObjectId("5ca2141da0106d1320c0ae32"), detail: 1},
{_id: ObjectId("5ca2141da0106d1320c0ae33"), detail: 3},
{_id: ObjectId("5ca2141da0106d1320c0ae34"), detail: 3}
];
const bulk = [];
input.forEach((datum) => {
bulk.push(
{
updateOne: {
"filter": {_id: datum._id},
"update": {$set: {detail: datum.detail}}
}
}
)
})
await db.collection.bulkWrite(bulk)
Version 4.2 introduced pipelined updates which allows us to use aggregation operators in the update body, now we can execute a single update and leverage this power, you can achieve the update in multiple ways here is one example:
const input = [
{_id: ObjectId("5ca2141da0106d1320c0ae32"), detail: 1},
{_id: ObjectId("5ca2141da0106d1320c0ae33"), detail: 3},
{_id: ObjectId("5ca2141da0106d1320c0ae34"), detail: 3}
];
db.collection.updateMany(
{ _id: {$in: input.map(v => v._id )}},
[
{
$set: {
detail: {
$getField: {
field: "detail",
input: {
$first: {
$filter: {
input: input,
cond: {
$eq: [
"$$this._id",
"$_id"
]
}
}
}
}
}
}
}
}
])
Mongo Playground