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

207
Views
Use array field in $cond

Im trying to set a value in my aggregation pipeline based on if any object in an array has a specific value set to true.

            {
                $set: {
                    "read": {$cond: {if: {"permissions.publicRead": true}, then: true, else: false}},
                    "write": false,
                    "owner": false
                }
            }

But its complaining about not allowing a "." in the field name. The data looks something like this:

{
    "permissions": [
        {"publicRead": true},
        {"publicRead": false}
    ]
}

Edit: I also tried using $permissions.publicRead and {if: "permissions.publicRead", then: true, else: false}

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Reason of error: $cond requires to check condition in $eq operator and need to pass $ before $permissions.publicRead in condition,

$cond: { 
  if: { $eq: ["$permissions.publicRead", true] }, then: true, else: false 
}

After resolving above problem the query will work without error but it will not return right result because, the permissions.publicRead will always return array of boolean values,

$eq: ["$permissions.publicRead", true]

is equal to

$eq: [[true, false], true] or $eq: [[false, true], true]

so

[true, false] or [false, true] is not equal to true


Try $anyElementTrue operator to check is array have any true value or not,

db.collection.aggregate([
  {
    $set: {
      "read": {
        $anyElementTrue: "$permissions.publicRead"
      },
      "write": false,
      "owner": false
    }
  }
])

Playground

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!