Converting strings into lists using MongoDB

Our MongoDB database currently stores order information with the "item_list" field as a string like

"item_list" : "[{\"item_id\":14243,\"price\":7500,\"quantity\":1},{\"item_id\":1424,\"price\":2500,\"quantity\":1}]"

I am looking for a way to convert this string into a list object.

The desired final format should be:

 "item_list" : [{item_id:14243,price:7500,quantity:1},{item_id:1424,price:2500,quantity:1}]

Answer №1

This situation seems quite messy, but fear not, I have a solution.

To resolve the issue with your invalid JSON, you will need to use the .parse() method:

 var bulk = db.collection.initializeOrderedBulkOp(),
     count = 0;

 db.collection.find({ "item_list": { "$type": 2 } }).forEach(function(doc) {

     doc.item_list = doc.item_list.replace(new RegExp("(\"quantity\":\\d+)","g"),"$1},");
     doc.item_list = doc.item_list.replace(new RegExp(",]$"),"]");
     doc.item_list = JSON.parse(doc.item_list);

     printjson(doc.item_list);

     bulk.find({ "_id": doc._id }).update({
         "$set": { "item_list": doc.item_list }
     });
     count++;

     if ( count % 1000 == 0 ) {
         bulk.execute();
         bulk = db.collection.initializeOrderedBulkOp();
     }

 });

 if ( count % 1000 != 0 ) {
     bulk.execute();
 }

I'm posting this because it appears that others may not have noticed the issues with the JSON data.

Answer №2

Assuming your data is structured as follows:

"product_list" : "[{\"product_id\":19832,\"price\":5500,\"quantity\":2},{\"product_id\":19833,\"price\":3500,\"quantity\":1}]"

Below is a script that can be used to update all records:

db.products.find().forEach(function(doc) {
    var products = JSON.parse(doc.product_list);

    db.products.update({
    "_id": doc._id
    }, {
    $set: {
        "product_list": products
    }
    });
});

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

Learn the process of sending data from a * .ejs file to app.js and managing click events on HTML tags within the app.js file

As I immerse myself in learning Node.js, EJS, MongoDB, Mongoose, and Express, I decided to test my knowledge by building a small application. To track my progress, you can find details of my project in this link: https://codesandbox.io/s/ecstatic-lichterma ...

When I click on the delete button in the dialog box, a horizontal scroll bar appears on the page

I'm dealing with a table that includes an 'approved' column with three conditions. One of these conditions triggers the appearance of a delete button along with a confirmation dialog box made using Vuetify's dialog component. The iss ...

Showing RSS feed on Vue.js interface

I am trying to integrate a Google Alert feed into my Vue.js application, specifically on the "Dashboard.vue" component using "Feed.vue". I have successfully implemented this feature in JavaScript, but I am facing difficulties converting it to Vue.js. Curr ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

What are the steps to integrate mp3 music into my web application?

Does anyone have experience implementing auto-resume mp3 music on a web application so that the music continues to play even when the user changes pages? I would like the music to seamlessly play as the user navigates through my web application. Can someo ...

The MERN app is now displaying data from MongoDB

After deploying my backend to Render.com and frontend to Netlify.com, I encountered an issue. While everything worked fine on localhost, it stopped working once deployed. The backend seems to be failing after deployment, as shown in this screenshot: Rende ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Save a specific collection of divs from a webpage as a PDF or Word document

Could the following scenario be achievable? Imagine a webpage containing a series of div elements with unique IDs or classes. Inside each div, there is a title (possibly an h1 tag) and some additional content. Is it possible to create a selection list of t ...

Top method for creating a personalized link for a user and storing information in their nodejs designated link

In the process of developing an application form that includes a reference section, I encounter the need to send an email to the specified reference once a user submits their application. The reference is then required to complete a form which will be link ...

Optimizing Performance with MongoDB's Compound Geo Polygon Indices

I am working with multiple geo queries that have a similar structure to the example provided below. These queries involve more than just a point in Poly query, they have other components as well. Example Query: { "point": { "$within": { "$pol ...

JWPlayer encounters an issue: "undefined" function is not defined

Can anyone lend a hand with this issue I'm facing? I'm attempting to upload a video using jwplayer but encountering errors. Here is the snippet of code I'm utilizing: <script type="text/javascript"> jwplayer("leg ...

Having trouble with PHP not receiving data when using a $.ajax POST request?

I'm facing an issue where my code seems to be correctly passing a JavaScript variable to PHP. On the JavaScript side, everything works fine - I receive success messages and see the data in the network tab. However, on the PHP side, I am unable to retr ...

What is the process for adding a data element to an array of objects in MongoDB, specifically based on the name in the completed array within the breakfast array?

I need to dynamically insert the current date into a user's meal plan for breakfast and locate an object like a banana based on certain conditions, then append the date to the completed array. This is the mongoose document structure. Each food item i ...

Adjust Ajax JSON query parameter

Here is the code I am currently working with: http://jsfiddle.net/spadez/nHgMX/2/ $(function() { function log( message ) { $( "<div>" ).text( message ).prependTo( "#log" ); $( "#log" ).scrollTop( 0 ); } $( "#city" ).autoco ...

Save numerous S3 pictures in MongoDB

I am facing an issue with storing multiple images in my database. Despite receiving a successful response in Postman confirming that multiple images have been saved, I later discover that only one image is actually stored in the database. Below is my mode ...

Obtaining numerous files in base64 along with their respective file names using FileReaderAPI in Javascript

When I upload 3 items named png1, png2, and png3, the result will be as follows: alert 1 png1 / base64 string conversion alert 2 png2 / base64 string conversion alert 3 png3 / base64 string conversion I experimented with this code snippet. fu ...

How can you apply the CSS styles of your grandparents without inheriting the styles of

Although it may seem unlikely, I still wanted to inquire about the possibility. <body> //body with 'back' background <div id="div1"> //div1 with 'front' background <div id="child1"> //c ...

The useState hook fails to update the value

Currently, I am using the onClick event to trigger setClickedMovieId. Additionally, I have implemented a useEffect hook to ensure that the state value is correctly set; however, it is logging out the default value of zero. The main goal here is to store t ...

Why is the updated index.html not loading with the root request?

I'm currently working on an Angular app and facing an issue with the index.html file not being updated when changes are made. I have noticed that even after modifying the index.html file, requests to localhost:8000 do not reflect the updates. This pro ...

Make sure to include !important for the hidden property when applying inline styles in React jsx

Is there a way to include !important in the hidden property within React JSX inline style? I'm attempting to conceal the scroll bar in an Ag Grid table component as it is displayed by default. I've already attempted: ref={(nod ...