Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace embedded fields in mongo DB

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading