'Using $exists in MongoDB $cond

For background, I have to create a field in a collection, but ONLY if another known field (an array) is not empty. I'm trying to make a boolean filter with the $and and some conditions:

$set: {
  clientsAllowed: {
            $cond: {
              if: {
                $and: [
                  {
                    businessAllowed: { $exists: true },
                  },
                  {
                    businessAllowed: { $type: "array" },
                  },
                  {
                    businessAllowed: { $ne: [] },
                  },
                ],
              },
              then: [...],
              else: [...],
            },
          }
}

But I get this error:

Invalid $set :: caused by :: Unrecognized expression '$exists'

Is the $exists wrongly formatted? Or is the $and stage? Any ideas?



Solution 1:[1]

Type cond for businessAllowed is enough. You don't need to check exists or not.

db.collection.aggregate([
  {
    $set: {
      clientsAllowed: {
        $cond: {
          if: {
            $and: [
              {
                "$eq": [
                  {
                    $type: "$businessAllowed"
                  },
                  "array"
                ]
              },
              {
                $ne: [
                  "$businessAllowed",
                  []
                ]
              }
            ]
          },
          then: [],
          else: []
        }
      }
    }
  }
])

mongoplayground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s