0

I have a document like this in mongo collection :

{

"_id" :"sdsfsfd323323323ssd",
"data" : {
        "('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [
            "$B_Add-Server", 
            "$B_Pool1_0_Server"
        ],
        "('State', \"Get-Server -Server 'uds412'\"):[
            "$B_Add-Server", 
            "$B_Pool2_0_Server"
          ]
}

and I need to update "uds412" to "newValue".

Someone please help , how to find and replace it ?

Thanks

uday214125
  • 569
  • 1
  • 8
  • 22
  • Possible duplicate of [How can I rename a field for all documents in MongoDB?](https://stackoverflow.com/questions/9254351/how-can-i-rename-a-field-for-all-documents-in-mongodb) – Vikash_Singh May 14 '19 at 09:33
  • @VikashSingh its not like rename the field. It find sub string and replace new string. – uday214125 May 14 '19 at 09:50
  • to find the field use `$exists`. `db.collection.update({'data.field': {$exists:true}},{$rename:{'data.field': 'data.newfield'}},{multi: true})` – Vikash_Singh May 14 '19 at 09:51
  • @VikashSingh here, key is : "('State', \"Get-Server -Server 'uds412'\") and need to find 'uds412' and this one has to be replaced. – uday214125 May 14 '19 at 10:02

2 Answers2

0

You can convert you valid JSON object into string and replace string to new value and again parse it into valid JSON object.

obj={ ...YOUR JSON OBJECT... }

newobj = JSON.parse(JSON.stringify(obj).replace('uds412','newValue'))
mukesh kudi
  • 719
  • 6
  • 20
0

Finally , i solve it like this, problem was , i need to find substring from key and update that key.

// first query the document

db.server_col.find().forEach(function (docs) {

    var tempData = {};
    var tempDataAr = [];

    for (var key in docs["data"]) {

        var find = /'uds412'/;

        if (key.match(find)) {
            tempDataAr = docs["data"][key]
            key = key.replace('uds412', 'newValue');
            tempData[key] = tempDataAr;
        } else {
            tempData[key] = docs["data"][key];
        }

    }
   print(tempData);
   // then you can update it
   db.server_col.update({ "_id" : ObjectId("sdfsfdafs")}, { $set: { 'data':tempData  } }, { multi: true })

});
uday214125
  • 569
  • 1
  • 8
  • 22