• Home
  • Jobs
  • coursesAndChallenges
  • Teachers
  • For business
  • Blog
  • ES/EN

0

20
Views
How to rename mongodb field using regex expression

I'm trying to update the name of a field in the mongodb document using the regex expression on the name of that field but I can't, can someone help me to do it? I have a person document that contains a field with the email of the person, the name of that field is like that "firstname_lastname@gmail.com" and I want to replace "_" character in all email fields by "_dot_". Here is what I did :

    db.getCollection("person").updateMany(
    {
      {'email.'+'.*_.*': { $exists: true }  
    },
    {
      $rename:{'email.'+'.*_.*': 'email.'+'.*_dot_.*'
    });

and here the structure of my document:

    person {
    name: { .... }
    email:{
     firstname_lastname1@gmail.com : {
       .... other fields
     },
     firstname_lastname2@gmail.com : {
       .... other fields
         }
        }
    }

thanks in advance

11 days ago ·

Santiago Trujillo

1 answers
Answer question

0

As @Wernfried Domscheit suggested in the comment, you should change your schema to avoid using dynamic email address as field name.

Nevertheless, you can use $objectToArray to convert the emails into an array of k-v tuples. Then, $split them by _ and rejoin by _dot_. Finally do a $arrayToObject to convert back to original structure.

db.collection.aggregate([
  {
    "$addFields": {
      "email": {
        "$objectToArray": "$email"
      }
    }
  },
  {
    "$addFields": {
      "email": {
        "$map": {
          "input": "$email",
          "as": "e",
          "in": {
            k: {
              "$ltrim": {
                "input": {
                  "$reduce": {
                    "input": {
                      "$split": [
                        "$$e.k",
                        "_"
                      ]
                    },
                    "initialValue": "",
                    "in": {
                      "$concat": [
                        "$$value",
                        "_dot_",
                        "$$this"
                      ]
                    }
                  }
                },
                "chars": "_dot_"
              }
            },
            v: "$$e.v"
          }
        }
      }
    }
  },
  {
    "$addFields": {
      "email": {
        "$arrayToObject": "$email"
      }
    }
  }
])

Here is the Mongo Playground for your reference.

11 days ago · Santiago Trujillo Report
Answer question
Remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Startups
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.