Is it possible to update part of a string within a documents

I need to update/replace the character ‘&’ within a string in the noteDesc string value (in bold below), I want to change the character from & to ‘and’. The below is part of my document.

{
“_id”: {
“$oid”: “613b605c62c5e40010c70dc4”
},
“section”: [{
“section_idx”: {
“$numberLong”: “0”
},
“premiumDetails”: {
“overrideOption”: “N/A”,
},
“systemNotes”: {
“note”: [{
"noteDesc": “FVEE at night exclusion added to Buildings & Contents cover.”,
“noteTypeKey”: 69,
“noteStatusKey”: 3
}

I have tried using the below script to make the update/replacement, but I haven’t been able to make it work. Any help anyone can give me would be greatly appreciated.

db.quoteSection.updateMany([ {

    $project: {
        noteDesc: {$replaceOne: { input: "$noteDesc", find: "&", replacement: "and"}}
    }
}

])

The other method I tried is:

db.quoteSection.findOneAndUpdate(
{
$and:
{“section.0.systemNotes.note.0.noteDesc”:{$regex: ‘&’}}
},
{
$set:{
“section.0.systemNotes.note.0.noteDesc”: “and”
}
},
{
arrayFilters : [
{
“section.0.systemNotes.note.0…noteTypeKey”: 69
}
]
}
);

Hi there @Corbin_Bridgeman,

Maybe $splitting at &, and then $concatenating?

I can’t access the docs right now, but would start there.

You are on the right track with $replaceOne. The complexity comes from have to work inside an array of array.

Simple $replaceOne example:

mongosh> c.find()
{ _id: 1, t: 'Buildings & Contents' }
mongosh> c.aggregate( { "$addFields" : { "result" : { $replaceOne: { input: "$t", find: "&", replacement: "and"} }}})
{ _id: 1,
  t: 'Buildings & Contents',
  result: 'Buildings and Contents' }

With complex array like yours you have to rely on $map.

When publishing documents it is best when we can cut-n-paste directly into our systems. To do so follow Formatting code and log snippets in posts.

Here is your redacted document. It will be easier to others to pitch in:

{ _id: 1,
  section: 
   [ { section_idx: 2,
       premiumDetails: 3,
       systemNotes: 
        { note: 
           [ { noteDesc: 'FVEE at night exclusion added to Buildings & Contents cover.',
               noteTypeKey: 69,
               noteStatusKey: 3 } ] } } ] }
3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.