Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

494
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!