1

I need to join two collection with two conditions.

products:
{
  ...
  sku: "4234",
  organizationId: ObjectId("asdasdasd);
  ...
};

order_history:
{
  ...
  itemSku: "4234",
  organizationId: ObjectId("asdasdasd);
  ...
} 

I chose pipeline approach:

$lookup: {
  from: 'order_history',
  let: { foreign_sku: "$itemSku", foreign_organizationId: "$organizationId" },
  pipeline: [
    {
      $match: {
        $expr: {
          $and: [
            { $eq: ["$organizationId", "$$foreign_organizationId"] },
            { $eq: ["$sku", "$$foreign_sku" ] }
          ]
        }
      }
    }
  ],
  as: 'order_history'
}

I wrote it on base of Mongo Documentation, but my conditions are ignored. I have scalar multiplication in result. Where is my mistake?

1
  • 1
    You need to join order_history with products. So you have added from:'order_history' in lookup. But let variables should be from product collection, not from order history collection. Your $itemSku and $organizationId are coming from order_history colelction Commented Jul 25, 2021 at 16:03

1 Answer 1

2

I already mention in the comment and the code is below

db.products.aggregate([
  {
    $lookup: {
      from: "order_history",
      let: {
        foreign_sku: "$sku",
        foreign_organizationId: "$organizationId"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$organizationId",
                    "$$foreign_organizationId"
                  ]
                },
                {
                  $eq: [
                    "$itemSku",
                    "$$foreign_sku"
                  ]
                }
              ]
            }
          }
        }
      ],
      as: "order_history"
    }
  }
])

Working Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.