Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string value to an integer in mongodb aggregation pipeline

In my NodeJs application where I am using MongoDb database and I have two collections products and market_companies both collections have a field name hub_id and dimensions here dimensions is an object field.I have created the aggregation pipeline where in both the collections I am comparing hub_id and dimensions field but here the thing is hub_id in products collection is an integer but in market_companies its an string due to which I am not getting desired output.

I want to know how can I convert hub_id to integer from string in market_companies collection.

Below is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     db.products.aggregate([
    {
    $lookup: {
      from: "market_companies",
      let: {
        hubId: "$hubId",
        dimensions: "$dimensions"
      },
      as: "companies",
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$hubId", // How to convert this into Integer
                    "$$hubId"
                  ]
                },
                {
                  $setEquals: [
                    {
                      "$objectToArray": {
                        $ifNull: [
                          "$dimensions",
                          {}
                        ]
                      }
                    },
                    {
                      "$objectToArray": {
                        $ifNull: [
                          "$$dimensions",
                          {}
                        ]
                       }
                     }
                   ]
                 }
               ]
             }
           }
         },
       ]
      }
     }
    ])   

Someone let me know any help appreciated.

>Solution :

You can do it with $toInt operator:

{
  $eq: [
    { $toInt: "$hubId" },
    "$$hubId"
  ]
},
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading