Home > Enterprise >  How to replace string in collection array with MongoDB 4.2
How to replace string in collection array with MongoDB 4.2

Time:03-19

I have below Mongo Collection

{
   "name":"test",
   "work":"BA",
   "contacts":[
      {
         "company":"xyz",
         "email":"http://www.google.com/check/com/2"
      },
      {
         "company":"xyz1",
         "email":"http://www.google.com/verify/com/4"
      }
   ]
}

I want to replace www.google.com from contacts email to www.test.com, Not complete URL only a particular string from email. Any help appreciated!!

CodePudding user response:

Query1

  • $indexOfCP MongoDB >=3.6

PlayMongo

aggregate(
[{"$set": {"m": "www.google.com", "r": "www.test.com"}},
 {"$set": 
   {"contacts": 
     {"$map": 
       {"input": "$contacts",
        "in": 
         {"$mergeObjects": 
           ["$$this",
             {"email": 
               {"$let": 
                 {"vars": {"index": {"$indexOfCP": ["$$this.email", "$m"]}},
                  "in": 
                   {"$cond": 
                     [{"$eq": ["$$index", -1]}, "$$this.email",
                       {"$concat": 
                         [{"$substrCP": 
                             ["$$this.email", 0, {"$subtract": ["$$index", 0]}]},
                          "$r",
                           {"$substrCP": 
                             ["$$this.email",
                               {"$add": ["$$index", {"$strLenCP": "$m"}]},
                               {"$subtract": 
                                 [{"$strLenCP": "$$this.email"},
                                   {"$add": 
                                     ["$$index", {"$strLenCP": "$m"}]}]}]}]}]}}}}]}}}}},
 {"$unset": ["m", "r"]}])

Query2

  • $replaceAll MongoDB >= 4.4

PlayMongo

aggregate(
[{"$set": 
   {"contacts": 
     {"$map": 
       {"input": "$contacts",
        "in": 
         {"$mergeObjects": 
           ["$$this",
             {"email": 
               {"$replaceAll": 
                 {"input": "$$this.email",
                  "find": "www.google.com",
                  "replacement": "www.test.com"}}}]}}}}}])

CodePudding user response:

4.2 :

db.collection.update({
 "contacts.email": {
  $regex: "google"
 }
 },
[
 {
   $addFields: {
     contacts: {
       $map: {
         input: "$contacts",
         as: "c",
         in: {
           $mergeObjects: [
            {
              email: {
              $replaceOne: {
                input: "$$c.email",
                find: "www.google.com",
                replacement: "www.test.com"
              },    
             }
            },
            {
               company: "$$c.company"
            }
           ]
          }
         }
        }
       }
      }
     ])

Explained:

Update via aggregation pipeline using replaceOne via $map/mergeObjects

playground

  • Related