Mongodb Update subdocument values matching subdocument and without altering other fields
You can use update with aggregation pipeline from MongoDB 4.2,
$map
to iterate loop of arraydoc
and inside it iterate throughupdateDocs
array, it will return matchingb
, and then$mergeObjects
will return updated document,
let updateDocs = [ { "_id": mongoose.Types.ObjectId("5f86cacbe4d7c423f21faf50"), "b": 90 }, { "_id": mongoose.Types.ObjectId("5f86cb01a1ca5124063299c1"), "b": 45 }];db.collection.updateMany({},[ { $set: { doc: { $map: { input: "$doc", as: "d", in: { $mergeObjects: [ "$$d", { $reduce: { input: updateDocs, initialValue: {}, in: { $cond: [ { $eq: ["$$this._id", "$$d._id"] }, { b: "$$this.b" }, "$$value" ] } } } ] } } } } }])