Seeking out and upgrading essential information: how to do it effectively?

I am working with a document in a mongo collection that looks like this:

{

"_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 change the value "uds412" to "newValue".

If anyone has a solution on how to find and replace it, please help!

Thank you

Answer №1

To update a JSON object, you can convert it to a string, replace the desired value, and then parse it back into a valid JSON object.

jsonData={ ...YOUR JSON DATA... }

updatedData = JSON.parse(JSON.stringify(jsonData).replace('oldValue','newValue'))

Answer №2

After tackling the issue, I approached it with the following solution: the problem lied in the necessity of finding a substring from a key and then updating that key.

// To begin, 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);
   // Now proceed with the update
   db.server_col.update({ "_id" : ObjectId("sdfsfdafs")}, { $set: { 'data':tempData  } }, { multi: true })

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a password strength checker using Javascript for ultimate security

Currently encountering an issue with my javascript project. The main goal is to validate user input against a list of known bad passwords and also their "1337" versions. Initially, checking for the basic bad password list was straightforward. However, th ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...

Enhance the connectivity of Angular js by activating the link function post transclusion

I am facing an issue with Angular where I have two directives that need to be transcluded within each other. However, I am unable to access the DOM using a simple JQuery selector after the transclude function has been executed. Specifically, I need to comp ...

What is the best way to transfer data between different states in ReactJS components?

I am in the process of developing an application that will showcase a list of categories. Upon selecting a category, the application will transition to the next page where a query regarding water type will be posed. Once the water type is chosen, the app s ...

Trigger an email notification in Google Sheets whenever a designated cell is populated

I am currently exploring ways to enhance collaboration in project management, especially when dealing with numerous stakeholders (Although there are free tools available, integrating new procedures into a public organization's projects can be quite ch ...

Strategies for Handling a High Volume of API Requests in Node JS

My journey with Node JS began recently, and I had a smooth start. I followed an online tutorial and successfully accepted a GET request in my server.js file. Coming from a Java background, I found myself with a handful of questions that I couldn't fi ...

Using Promise.all within the useEffect hook in ReactJS

I encountered a scenario where I needed to make two API calls one after another, with the second call dependent on the response from the first one. Fortunately, I managed to utilize the Promise.all function along with axios in my React project. However, I ...

Even with the use of setTimeout, Angular 5 fails to recognize changes during a lengthy operation

Currently, I am facing an issue with displaying a ngx-bootstrap progress bar while my application is loading data from a csv file. The Challenge: The user interface becomes unresponsive until the entire operation is completed To address this problem, I a ...

Is there a way to connect the select2 plugin to a select element that contains plugin options in a JSON object stored in the data attribute?

Utilizing various select2 plugins, I am looking to set the options and values of the plugin based on the data attributes of related elements. The following is an example: HTML <select data-plug="select2" data-plug-op='{"placeholder":"text1","con ...

Having trouble creating a table using a JSON object in AngularJS

Click here to view the converted JSON object Please pay close attention to my question Hello, in the code below I am attempting to convert XML data into a JSON object. With this converted JSON object, I am aiming to create a table using AngularJS. The is ...

Find a specific row in a table using jQuery without requiring any input from the

I want to create a search function that filters results in a table based on user input. The script I have currently works but I need it to only search the first column without requiring the user to click an input field. I want the default value to load whe ...

What methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

Mutual TLS authentication and secure tunneling with ngrok

I am currently working on integrating a Payment Method with Shopify that requires me to validate their client requests using mTLS. Payment apps must utilize mTLS for processing all requests where they act as the server and Shopify as the client. This is ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

Save the file to a specific folder and compress the entire folder into a

I have encountered an issue while attempting to write a file to a directory named templates and then stream a zip file with the content that was just written. The problem arises when the zip file is returned, displaying an error message "Failed - Network E ...

Simple steps to transform an array of elements into an object within a MongoDB projection

I'm having trouble understanding how to use $project and $arrayToObject. In my MongoDB query, I get an array of objects: [{ amounts: [ 10, 20, 30 ], id: "0x3c93" }, { amounts: [ 0, 0, 100 ], id: "0xee10" }] I want to group the res ...

Azure SQL Server linked with a REST API built on Express.js/Node.js encountered an error stating: "TypeError: req.sql is not a function"

Having trouble connecting to Azure SQL Server with express4-tedious. I'm working on building an app in react-native with a Node/Express server (REST API), but encountered this error after setting up express4-tedios in Express: req.sql is not a functio ...

What is the reason behind my page automatically scrolling to the bottom when it loads?

I am currently working on a project for my company, and unfortunately, I cannot share the code as it is proprietary. However, I am encountering a problem where the page loads and automatically scrolls to the bottom. I have checked for any unclosed tags in ...

What is the process for retrieving and utilizing data from a previous MongoDB database stored on a secondary drive?

Having encountered a situation where one of my Windows 10 PCs with MongoDB 3.6 running on it faced a motherboard failure, I am now faced with the challenge of accessing the old MongoDB database from the previously used hard drive (now designated as Drive E ...