MongoDB aggregate for simple array spesific value replace and convert

Viewed 48

I'm stuck somewhere about Mongodb aggregate about array modification.

my array looks like this:

[
  {
    location: {
      open: true,
      expected: [
        "foo",
        "bar",
        "baz"
      ]
    }
  }
]

I wanna find and replace specific value and convert to ObjectId.

I have tried using this pipeline:

[
    {
        $match: {
            "location.expected": {$eq: "foo"}
        },
    }
    {
        $set: {
            "location.expected": {
                $map: {
                    input: "$location.expected",
                    as: "loc",
                    in: {
                        $replaceAll: {
                            input: "$$loc",
                            find: "foo",
                            replacement: "60783e804136605b0a48bfe8"
                        }
                    }
                }
            }
        }
    }
]

it work now. but I cannot convert to ObjectId, replaced value.

so, I simple solution about find & replace & convert specific simple array value.

thanks for all.

1 Answers

You just want to cast the string into ObjectId, like so:

db.collection.aggregate([
  {
    $match: {
      "location.expected": "foo"
    }
  },
  {
    $set: {
      "location.expected": {
        $map: {
          input: "$location.expected",
          as: "loc",
          in: {
            $cond: [
              {
                $eq: [
                  "$$loc",
                  "foo"
                ]
              },
              ObjectId("60783e804136605b0a48bfe8"),
              "$$loc"
            ]
          }
        }
      }
    }
  }
])

As you can see I changed your pipeline by a little, I personally do not recommend using $replaceAll for this use case as it's a more expensive action and is tailored to be used as a regexp and less as an exact match operator.

Mongo Playground

Related