Home > OS >  MongoDB - Replace embedded fields
MongoDB - Replace embedded fields

Time:03-24

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 椰果"]]

CodePudding user response:

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

  • Related