What is the best way to transform string values to numbers when mapping an array of objects in MongoDB?

My documents contain a field called "details" which is an array:

 {   
        "_id" : ObjectId("60ae0b29ab282518443c7ac5"),
        "details": [
              {
                "label": "Asset title",
                "value": "S1",
              },
              {
                "label": "Total Cost",
                "value": "250",
              },
              {
                "label": "Possession Status",
                "value": "Available",
              },
              {
                "label": "Estimated Monthly Rent",
                "value": "15.5",
              }
            ]
    },
    {   
        "_id" : ObjectId("60ae0b29ab282518443c7ac8"),
        "details": [
              {
                "label": "Asset title",
                "value": "S2",
              },
              {
                "label": "Total Cost",
                "value": "455.5",
              },
              {
                "label": "Possession Status",
                "value": "Available",
              },
              {
                "label": "Estimated Monthly Rent",
                "value": "30",
              }
            ]
    }

I am currently attempting to $project this array of objects by mapping through each object and converting certain string values to numbers when the label is either "Total Cost" or "Estimated Monthly Rent". For example, for {label = "Total Cost"}, I want to use: {"$toDouble" : value}, and for

{label = "Estimated Monthly Rent"}
, I want to apply: {"$toDouble" : value}.

However, my attempt to do so is resulting in an error.

 db.collection.aggregate([
       {
             "$project": {
                                   
                    "data": {
                         "$map": {
                                "input": "$details", 
                                 "as": "val", 
                                 "in": {
                                 "$cond":{ if: {"$$val.label": "Total Cost"} , then: { "$toDouble" : "$$val.value"}},
                                 "$cond":{ if: {"$$val.label": "Estimated Monthly Rent"} , then: { "$toDouble" : "$$val.value"}}
                                  }
                         }
                     } 
              }
        }
    ])

Answer №1

Verify the condition using the $in operator, then return the converted value if there is a match; otherwise, return the original object.

db.collection.aggregate([
  {
    "$project": {
      "data": {
        "$map": {
          "input": "$details",
          "as": "val",
          "in": {
            $cond: [
              { $in: ["$$val.label", ["Total Cost", "Estimated Monthly Rent"]] },
              {
                label: "$$val.label",
                value: { $toDouble: "$$val.value" }
              },
              "$$val"
            ]
          }
        }
      }
    }
  }
])

Access the Playground here

Answer №2

Your query is experiencing an issue due to the presence of two keys for $cond within the in field. Instead, utilize only one key and incorporate the $or operator. Additionally, ensure to use $eq for equality matching in the aggregation pipeline, and do not forget to include the else clause in $cond.

Here is a revised version of your query:

db.collection.aggregate([
  {
    "$project": {
      "data": {
        "$map": {
          "input": "$details",
          "as": "val",
          "in": {
            "$cond": {
              if: {
                $or: [
                  {
                    "$eq": [
                      "$$val.label",
                      "Total Cost"
                    ]
                  },
                  {
                    "$eq": [
                      "$$val.label",
                      "Estimated Monthly Rent"
                    ]
                  }
                ]
              },
              then: {
                "$toDouble": "$$val.value"
              },
              else: {
                "$toString": "$$val.value"
              }
            }
          }
        }
      }
    }
  }
])

You can test this query here.

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

Obtain the outline shape in ThreeJS (duplicate border)

When working with a geometry, I often need to view it from different angles. For example, if I position my camera from the top, I want to be able to extract the outline of the geometry as a new shape. This allows me to then Extrude this shape further. In R ...

Retrieving a specific value from a data object using Javascript

Having a data object, I am looking to extract a specific value from it. When attempting to output the data: console.log(data); I receive an object resembling the one shown in the image below : https://i.sstatic.net/OPhgH.png The issue lies in my at ...

Issue with Remote Cookie Setting, Functions Properly Locally

As I work on a basic Django app, one of my main concerns is ensuring that my csrftoken is properly set in order to successfully post responses. Interestingly, when testing locally and inspecting the JavaScript debugger, everything seems to be functioning c ...

Tips for using the findByIdAndUpdate function in MongoDB?

I am new to coding and struggling with how to properly use MongoDB. My issue involves updating the content of a selected comment within a parent object called classroom, which contains an array of comments. Initially, I updated the state of the entire "cl ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

What is the best way to postpone the angular animation until after the model has been bound

I am currently working on a project using AngularJS where I am implementing animations for state transitions. To help with this process, I have been referring to the angular wiki and found this Plunker example: http://plnkr.co/edit/NsZhDL?p=preview My is ...

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

"Is there a way to verify the existence of checkbox array values within a database using PHP Laravel

In order to display checkboxes for each country that exists in the database, I need to verify if the countries in the database match with those in the list. Since the values are retrieved directly from the database and can't be set as input values due ...

Converting MiniZinc CSP to JSON using a workaround for iterating through arrays in JavaScript

Utilizing the node.js module "Governify CSP Tools" to tackle a CSP issue has been challenging. Despite following the guidelines on defining an array from the CSP model schema (https://www.npmjs.com/package/governify-csp-tools), I have encountered syntax er ...

Detecting changes in the style of an HTML element using YUI3

Working on a website that is utilizing an unreliable ads provider. Occasionally, the JavaScript code they provide contains bugs, such as changing the background color of the entire body element instead of just its designated div. Unfortunately, we are stuc ...

The element type 'HTMLElement' does not contain a property named 'pseudoStyle'

Currently experimenting with adjusting the height of a pseudo element using Typescript. An error is popping up in my IDE (vscode) as I go along. This is the code snippet I am working with. // choose element let el: HTMLElement = document.getElementById( ...

Retrieving an attribute through the act of clicking a button

How can I retrieve the rel attribute value when clicking on a button with the class selector? <button class="nameClass" rel="relName">Content</button> I am attempting to achieve this by: $(".nameClass").click(function(){ // Here is where ...

Sending session cookies from javascript to php through ajax requests

Is there a way to pass session variable from JavaScript, considering that the JavaScript is generated from PHP? echo "<script>" ."if(confirm('Evaluation is already exist! Do you want to update evaluation?')) { //Here I want to add : ...

Having trouble establishing a connection between the webservice and mongodb

I've developed an Android application that performs SOAP requests to my Tomcat server. The server hosts a web service (MongoService.wsdl) which calls another class (DataLayer.java) containing a static method (getConnection). However, the initializatio ...

The Redux store is duplicating the state across different reducers, causing it to appear twice

Having Trouble Viewing Different States for Two Reducers in Redux DevTools In my React project, I am attempting to incorporate a second reducer using Redux to gain a better understanding of the overall state. However, when I inspect the state in Redux Dev ...

"if the condition is not met, the outcome will not be shown in the while

I have a looping structure that includes conditions for if, else if, and else. However, I have noticed that the else condition at the end of the loop is not being executed as expected. I am currently investigating why this might be happening. Here is the ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

How to retrieve a value from PHP using Ajax?

I am struggling to implement ajax for adding a div to display an error message. Despite my efforts, I keep receiving null as the error message instead of the expected value. The occurrence of null is traced back to <?php echo json_encode($_SESSION[&ap ...