0
{
  field:"value",
  facilityId:"H001",
  alternativeId:["deafaultID#12312-213-1314"],
}

I want to replace all the document "defaultID" from the array of alternativeId and change to "NEWID" only if the facilityId is "H001"

2
  • you can use $replaceOne and $map operators. Commented Jun 7, 2021 at 8:03
  • how.. can you give me a example Commented Jun 7, 2021 at 8:13

1 Answer 1

2
  • match facilityId: "H001" condition
  • $map to iterate loop of alternativeId array
  • $replaceOne to replace find string by replacement
db.collection.update(
  { facilityId: "H001" },
  [{
    $set: {
      alternativeId: {
        $map: {
          input: "$alternativeId",
          in: {
            $replaceOne: {
              input: "$$this",
              find: "deafaultID",
              replacement: "NEWID"
            }
          }
        }
      }
    }
  }],
  { multi: true }
)

Playground

Sign up to request clarification or add additional context in comments.

3 Comments

i edited my qstn . actually i want to check facilityid as condition or filter. only replace the alternativID of a specified facilityID
okay you want to update in database or just need to format result only?
@Alfjoy have you checked updated answer it is working?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.