What is the best way to change a String into an Array within MongoDB?

I need help with converting the type of an object that has been changed.

Is there a way to transform this:

{ 
"_id" : NumberLong(257),
"address" : "street  Street, house 50, appartment 508, floor 5"
}

into this:

{ 
"_id" : NumberLong(257),
 "userAddressList" : [{
        "street" : "Street",
        "house" : "50",
        "building" : "",
        "appartment " : NumberLong(508),
        "entrance" : NumberLong(0),
        "floor" : NumberLong(5),
        "intercom" : ""
    }]
}

using the mongo shell?

I have around 350 entries to convert, so I'm hoping it can be done through a script.

Answer №1

Here's a suggestion you can try:

db.collection.find().forEach( function (x) {   
    lines = x.address.split(",");
    obj = {};
    userAddressList = [];
    lines.forEach( function (address){
        addressArray = address.replace(/^\s\s*/, '').replace(/\s\s*$/, '').split(" ");
        obj[addressArray[0]] = !isNaN(parseInt(addressArray[1])) ? parseInt(addressArray[1]) : addressArray[1];        
    });
    obj.building = "";
    obj.intercom = "";
    userAddressList.push(obj);
    x.userAddressList = userAddressList; // convert field to string
    db.collection.save(x);
});

To convert the document into the desired format, you can utilize the MongoDB aggregation framework. Use the $addFields, $regexFind, and $convert operators to extract, transform, and load new fields.

Below is an aggregation pipeline that can help achieve the desired outcome:

db.collection.aggregate([
  { $addFields: {
      userAddressList: {
        $let: {
          vars: {
            street: {
              $regexFind: { input: "$address", regex: /(\w+)\s+Street/ }
            },
            house: {
              $regexFind: { input: "$address", regex: /house\s+(\d+)/ }
            },
            appartment: {
              $regexFind: { input: "$address", regex: /appartment\s+(\d+)/ }
            },
            floor: {
              $regexFind: { input: "$address", regex: /floor\s+(\d+)/ }
            }
          },
          in: [
            {
              street: "$$street.match",
              house: "$$house.match",
              building: "",
              appartment: {
                $convert: {
                  input: "$$appartment.match",
                  to: "long",
                  onError: NumberLong(0),
                }
              },
              entrance: NumberLong(0),
              floor: {
                $convert: {
                  input: "$$floor.match",
                  to: "long",
                  onError: NumberLong(0)
                }
              },
              intercom: ""
            }
          ]
        }
      }
    } },
    { $project: { address: 0 } }
]);

Answer №2

One way to implement a foreach loop in an update is by using the following code snippet:

db.example.find( { } ).forEach( function (item) {<br>
  item.userAddressList = item.address.split(" ");
  db.example.save(item);
});

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

How can I extract a substring using jQuery?

<script type="text/javascript"> $(function(){ $("a[rel='tab']").click(function(e){ e.preventDefault(); pageurl = $(this).attr('href'); $.ajax({url:pageurl+'?rel=tab',success: function(data){ $(&apos ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...

The custom created THREE.Curve is not rendering correctly

Following advice from this solution, I have implemented a linearly interpolated curve in the code below: THREE.Linear3 = THREE.Curve.create( function ( points, label /* array of Vector3 */) { this.points = (points == undefined) ? [] : points; ...

Displaying a random number triggers a snackbar notification in a ReactJS application

Currently, I am utilizing the notistack package to display a snackbar on the screen. However, when calling the Snack component with enqueuesnackbar, a random number is displayed along with the snackbar. I'm looking to eliminate this random number fro ...

Relaunch node.js in pm2 after a crash

Based on this post, it seems that pm2 is supposed to automatically restart crashed applications. However, when my application crashes, nothing happens and the process no longer appears in the pm2 list. Do I need to enable an 'auto restart' featu ...

How can JQuery be used to implement "scrolling" buttons and automatically update the main page with fresh data?

I am attempting to achieve the following: 1 - Use jQuery to update index.html with the content from output.html (only update when there are differences in data, and ideally only update the parts that have changed). 2 - Add two buttons in the header ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

What is the reason for the error that is being caused by using arrow functions in my code

I'm currently working on a React application, but I keep running into errors that are causing issues. Here is the code snippet in question: import React from 'react'; import { Link } from 'react-router-dom'; const LINKS = [ { to ...

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

The jQuery animate() method fails to execute animations

I'm currently working on a JavaScript animation project and I've run into some roadblocks. One particular issue I'm facing is with animating the <label>'s margin-top, as it's not behaving as expected. For example: $(' ...

Restrict the number of items in each list to just one

I'm trying to customize a query that displays a list of numbers. My goal is to only display each unique number once. For example, if there are three instances of the number 18 in the database, I want it to show as 18, 18, 18. If there are two occurre ...

What is the best way to use JavaScript to emphasize a substring that includes a wild card character surrounded by two specific characters

In the dataframe below, I have multiple strings stored: v1 v2 ARSTNFGATTATNMGATGHTGNKGTEEFR SEQUENCE1 BRCTNIGATGATNLGATGHTGNQGTEEFR SEQUENCE2 ARSTNFGATTATNMGATGHTGNKGTEEFR SEQUENCE3 I am interested in searching for a ...

Need to specify a parameter type for the input tag in HTML

Currently, I am developing a customized focus method for my webpage using the following script: <script type="text/javascript"> function myFunction() { document.getElementById("name").focus(); } </script> I ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...

Load data into data tables through AJAX request

I'm currently working on implementing datatables and I'm facing an issue with populating my data table using an AJAX call. Here is the snippet of my AJAX call: $('#call_analysis_basic_table').DataTable ({ "ajax": { "url": " ...

Asynchronous behavior in Node.js and MongoDB when using await for patch requests

After encountering an issue with syncing returns while using await, it became apparent that the problem lies within the response handling. While all the information successfully updates in MongoDB, the endpoint res.status(200).send(updatedData); ends up re ...

Issues with jQuery requests not working properly on the mobile application

Creating a mobile application for Android devices using Intel XDK has been a rewarding experience so far. I have been testing my PHP code on an emulator and local development server (127.0.0.1) through AJAX methods such as $.ajax(), $.post(), and $.get(). ...

Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this: angular.module( 'example', [] ).directive( ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...