Dividing a string into separate components with JavaScript within the mongo shell

Within my mongo collection, there is a string labeled range = "2000 - 3000 INR". I am aiming to convert this string into an object where range = { min: 2000, max: 3000, currency: "INR"}. The structure of my collection is as follows:

{
  "id": "ABC",
  "places": [
    {
      "isSearchable": true,
      "locations": [
        {
          "id": "DEL",
          "loc": {
            "range": "2000-5000 INR"
          }
        },
        {
          "id": "BLG",
          "loc": {
            "range": "1000-3000 INR"
          }
        }
      ]
    }
  ]
}

I am aware that a JavaScript function can be implemented in the mongo shell to achieve this, but I am uncertain about the next steps. My initial attempt looks like:

cursor = db.getCollection('locations').find({"places.isSerachable":true});



// Iterate over Cursor object
while(cursor.hasNext()) {
item = cursor.next();
keys = Object.keys(item);

// Iterate over MongoDB doc fields
for (i=0; i-keys.length; i++) {
let field = keys[i];
print( "field:", field, "---",item[keys[i]]);
}

}

Your guidance on this matter would be greatly appreciated!

Answer №1

Do it this way

let info = { "id": "XYZ", "dataPoints": [{ "isSortable": true, "details": [{ "key": "ABC", "info": { "value": "100-200 USD" } }, { "key": "DEF", "info": { "value": "50-150 USD" } }] }

info.dataPoints[0].details.forEach(detail => {
  const [ minVal, maxVal, currency ] = detail.info.value.split(/[ -]/g)
  detail.info.value = { minVal, maxVal, currency }
})
console.log(info)

Answer №2

Check out this solution:

Here is a suggested code snippet to solve the problem:
const obj = {
  "id": "ABC",
  "places": [{
    "isSearchable": true,
    "locations": [{
        "id": "DEL",
        "loc": {
          "range": "2000-5000 INR"
        }
      },
      {
        "id": "BLG",
        "loc": {
          "range": "1000-3000 INR"
        }
      }
    ]
  }]
}

// Perform mapping operation on object places and locations
const result = obj.places.map(x => ({
  ...x,
  locations: x.locations.map(y => ({
    ...y,
    loc: {
      range: (() => {
        [min, max, currency] = y.loc.range.replace('-', ' ').split(' ');
        return {
          min,
          max,
          currency
        }

      })()
    }
  }))
}))

// Log the result in the console
console.log(result)

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

React-Webcam: What is the solution for the error "Object may be null" and how to resolve "Type null is not compatible with type string or undefined"?

I'm encountering an issue with const imageSrc = webcamRef.current.getScreenshot(); Error: Object is potentially 'null'; and src={imgSrc} <img src={imgSrc} /> Error: Type 'null' cannot be assigned to type 'string | und ...

Utilizing Modernizr.prefixed correctly in implementing transition and transform features specifically for Safari

I am currently working on a function that animates elements on a webpage by adding inline styles to the elements. In its simplest form, it adds the following styles: <div style="transition: transform 0.5s; transform: translateX(100px);">...</div& ...

Tips for positioning D3 circles along a half-circle arc

I'm trying to align a series of radios in a semi-circle formation, created from circles. The number of radios will vary and I need to ensure they stay centered. Here is my current setup: UPDATE: I just noticed that the order of the radios in the scre ...

The nullish coalescing operator in JavaScript is running code on both of its sides

console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist'); console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exis ...

What could be the reason my mat-form-field is not displaying the label?

I'm currently working on a project using Angular Material to build a web page. I am facing an issue with the mat-form-field component as the label is not displaying, and I can't figure out why. Any assistance would be greatly appreciated. Thank y ...

User must wait for 10 seconds before closing a JavaScript alert

Can a JavaScript alert be set to stay open for a certain amount of time, preventing the user from closing it immediately? I would like to trigger an alert that remains on screen for a set number of seconds before the user can dismiss it. ...

Tips on achieving Google indexation for AngularJS web applications

I've developed a single page application with AngularJS where all requests are directed to the index.html. Angular then handles the routing and pulls data from a set of API endpoints for display. The site's title, SEO metadata, and description a ...

Unable to convert value to ObjectID

I am receiving an array of names (String) in my body and I want to convert each name to its corresponding object ID from my Collection. My goal is to reference Strings to a Schema and replace them with their ObjectIds. This is the Schema I am using: ...

What are the steps to implementing PNG masking using PixiJS?

I am currently working on incorporating a png sprite as a mask for another layer. I found a demo on the pixi.js official website and created this fiddle: https://jsfiddle.net/raphadko/ukc1rwrc/ The code snippet below is what I am using for the masking fu ...

Incorporating JS objects into HTML: A comprehensive guide

Here is a snippet of code from my JavaScript file: var formStr = "<h5>How many books?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick=& ...

What is the best way to reassess the quantity of a specific element once a for loop has finished executing?

const removeBtnCustom = document.querySelectorAll('.customRemove'); for(let i=0; i<removeBtnCustom.length; i++){ removeBtnCustom[i].addEventListener('click', ()=>{ const itemToDelete = document.querySelectorAll('. ...

Is there a way to obtain the value of the <h3> tag for a checked radio button?

New.html.erb <div id="monthly_plan"> <% @monthly_plans.each_with_index do |plan, index| %> <div class="col-sm-6"> <input type="radio" name="subscription[plan_id]" id="plan_<%= plan.try(:id) %>" value="<%= p ...

I am curious about the inner workings of the `createApplication()` function in the ExpressJS source code. Can you shed some light on

My goal is to deeply comprehend the inner workings of the Express library, step by step. From what I gather, when we import and invoke the 'express()' function in our codebase, the execution flow navigates to the ExpressJS library and searches fo ...

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...

React components experiencing conflicts when using shorthand inline styles that overwrite one another

Within my React component, I am receiving a values object with attributes like: {gridColumn: '1 / 3', gridRow: '2 / 5', gridArea: 'header'} I apply these values to the component's style as follows: this.cell.style.setP ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Navigating and Organizing in Ionic Service Factory

Apologies for the beginner question. I am looking to incorporate filtering and sorting by name on my webpage. However, I have encountered two issues after attempting to implement this functionality using a factory in services.js: When typing a search ter ...

Utilizing jQuery Deferred or Promise to synchronize the completion of multiple asynchronous $.post requests

I'm attempting to make three separate jQuery posts, storing their results in variables that are accessible outside of their scope. Once all three posts have returned successfully, I want to execute another function. Currently, I am using nested callba ...

Using v-on:click to dynamically update multiple sections of content in a Vue.js and Liquid environment

Whenever I click on a button, I want the text and image to change. I attempted to do this but encountered difficulties in updating multiple elements simultaneously. {% for variant in product.variants %} <label for="variant_{{- variant.id }}"&g ...

How can a single item be selected from an array of instances in MongoDB?

Currently, I am working with MongoDB using Mongoose on NodeJS. { "_id":{"$oid":"5fa4386f3a93dc470c920d76"}, "characters":[ {"$oid":"5fa4389e3a93dc470c920d78"}, {"$oid":"5fa4 ...