skip to Main Content

How to check if a field is not existing inside lookup expression? The answers in similar questions are not helpful (e.g. {$eq : null} or $exists:true).

For example, I want to lookup inventory only if disabled is not existing.

db.orders.aggregate([
  {
    $lookup: {
      from: "inventory",
      let: {item: "$item"},
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: ["$sku", "$$item" ]
                },
                {
                  $eq: [ "$disabled", null ]
                }
              ]
            }
          }
        },
      ],
      as: "inv"
    }
  }
])

A playground sample is here

2

Answers


  1. you could use:

    { $match: { someField: { $exists: true } } }
    

    before the look up, to filter out the documents that you do not want to look up

    Login or Signup to reply.
  2. You can use $exists outside the $expr:

    db.orders.aggregate([
      {
        $lookup: {
          from: "inventory",
          let: {item: "$item"},
          pipeline: [
            {
              $match: {
                $and: [
                  {$expr: {$eq: ["$sku", "$$item"]}},
                  {disabled: {$exists: false}}
                ]
              }
            }
          ],
          as: "inv"
        }
      }
    ])
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search