Home > OS >  Check for non-existing field in lookup pipeline
Check for non-existing field in lookup pipeline

Time:06-15

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

CodePudding user response:

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

CodePudding user response:

you could use:

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

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

  • Related