Digvijay
Digvijay

Reputation: 3271

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

In my NodeJs application I am using MongoDB database. I have two collections products and market_companies. Both collections have a field name hub_id and dimensions, and 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 the thing is hub_id in products collection is an integer but in market_companies it's 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",
                          {}
                        ]
                       }
                     }
                   ]
                 }
               ]
             }
           }
         },
       ]
      }
     }
    ])   

Upvotes: 1

Views: 463

Answers (1)

NeNaD
NeNaD

Reputation: 20304

You can do it with $toInt operator:

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

Upvotes: 1

Related Questions