Home > Software engineering >  How to convert string value to an integer in mongodb aggregation pipeline
How to convert string value to an integer in mongodb aggregation pipeline

Time:01-01

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:

     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.

CodePudding user response:

You can do it with $toInt operator:

{
  $eq: [
    { $toInt: "$hubId" },
    "$$hubId"
  ]
},
  • Related