Shibu
Shibu

Reputation: 510

MongoDB - Join on multiple condition

For the below query

SQL:

SELECT * FROM TableA as A LEFT JOIN TableB as B ON (A.id = B.id AND A.name =B.name)

Mongo:

TableA.aggregate([
    {"$lookup": {
                "from": "TableB",
                "localField": "_id",
                "foreignField": "_id",
                "as": "b"
                }},
                { "$match": {  "name":"b.name" } }

])

For the above query, required output is not coming.

Upvotes: 0

Views: 351

Answers (1)

Gibbs
Gibbs

Reputation: 22956

You could refer this sample playground

db.orders.aggregate([
  {
    "$lookup": {
      from: "inventory",
      let: {
        id: "$_id",
        item: "$item"
      },
      pipeline: [
        {
          "$match": {
            $expr: {
              "$eq": [
                "$_id",
                "$$id"
              ],
              "$eq": [
                "$sku",
                "$$item"
              ]
            }
          }
        }
      ],
      as: "outputs"
    }
  }
])

Reference

Upvotes: 1

Related Questions