Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 830
Buenaventura Pino Moslero Avatar asked Oct 15 '25 06:10

Buenaventura Pino Moslero


1 Answers

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

like image 64
YuTing Avatar answered Oct 18 '25 02:10

YuTing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!