0

I have the following collection:

[
  {
    "_id": "6021d4e8de525e00bb3623f1",
    ...otherFields,
    "addonGroups": [
      {
        "_id": "6021d474143dbb00da601e6a",
        ...otherFields,
        "addons": [
          {
            "name": "Nike\t珍珠",
            ...otherFields,
          },
          {
            "name": "Adidas\t椰果",
            ...otherFields,
          },
          
        ]
      }
    ],
    
  }
]

I want to replace the \t character for whitespace " " on all the addons name field

I have the following:

db.collection.aggregate([
  {
    $addFields: {
      "addonGroups.addons.name": {
        $replaceAll: {
          input: "$addonGroups.addons.name",
          find: "\t",
          replacement: " "
        }
      }
    }
  }
])

I am getting this error:

query failed: (Location51746) PlanExecutor error during aggregation :: caused by :: $replaceAll requires that 'input' be a string, found: [["Nike 珍珠", "Adidas 椰果"]]

1 Answer 1

1

You can work with $map operator.

db.collection.aggregate([
  {
    $set: {
      addonGroups: {
        $map: {
          input: "$addonGroups",
          as: "addonGroup",
          in: {
            "$mergeObjects": [
              "$$addonGroup",
              {
                "addons": {
                  $map: {
                    input: "$$addonGroup.addons",
                    as: "addon",
                    in: {
                      $mergeObjects: [
                        "$$addon",
                        {
                          "name": {
                            $replaceAll: {
                              input: "$$addon.name",
                              find: "\t",
                              replacement: " "
                            }
                          }
                        }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground

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

9 Comments

Thanks a lot, addons do have other fields. Where should I place this last part you added?
Ya, I have update my answer.
For the MongoDB version 4.4 before, you can look for this solution.
@DanielMorales You could add a "$merge" stage to the end of the pipeline.
And also you may have a look on Updates with Aggregation Pipeline.
|

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.