Update array objects by condition

Prasad_Saya
Mon, 21 Feb 2022 09:37:33 +0000

Hello @Bora, welcome to the MongoDB Community forum!

I looked into your code and it is difficult to tell what the issue is - some data used in the query is not there for me to figure the problem. But, I have the below update operation which works in the mongosh or mongo shell. Let me know if this works. Note that the update uses a Aggregation Pipeline (this feature is Updates with Aggregation Pipeline).

var scanUuids = [ "fdec656b-071d-4a5a-9fd0-1a4258313a7d", "b922a852-2b69-470e-b5a0-80b7d01b4c80", "..." ]
var statusToUpdate = "some_value"

db.collection.updateOne(
{ _id : ObjectId("61fa721407b98252591852fd") },
[
  { $set: {
      urls: {
          $map: {
              input: "$urls",
              as: "url_doc",
              in: {
                  $cond: [
                      { $in: [ "$$url_doc.scanUuid", scanUuids ] },
                      { $mergeObjects: [ "$$url_doc", { status: statusToUpdate } ] },
                      "$$url_doc"
                  ]
              }
          }
      }
  }}
]
)