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

275
Views
Check for value to be in an array in $cond

Im trying to project a value in my aggregation pipeline based on if any array in an array contaibns a specific value.

This is a simplified version of how the data looks:

[
  {
    "permissions": [
      {
        "owners": [
          "1"
        ]
      }
    ]
  },
  {
    "permissions": [
      {
        "owners": [
          "2",
          "3"
        ]
      }
    ]
  }
]

And Ive tried to do the following (with "2" being the example value I am searching for):

{
    "$project": {
      owner: {
        $cond: {
          if: {
            $in: [
              "2",
              "$permissions.owners"
            ]
          },
          then: true,
          else: false
        }
      }
    }
  }

Playground Example

But it always ends up being false. Any ideas?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The problem is $permissions.owners is a nested array. Check this example to look that.

So you have to $unwind the array. But, if there is only one array you can look for into first position in the array like this

But, assuming there could be many arrays, you can use this query.

  • $unwind the array to get each value separated.
  • $set the value into owner variable if exists the number 2.
  • $group to get values again.

At this point, exists a variable called owner which is a boolean array. So the next step is similar to the query you have.

  • $set again to know if exists true in any value, so, the variable will be true too.
db.collection.aggregate([
  {
    "$unwind": "$permissions"
  },
  {
    "$set": {
      "owner": {
        "$in": [
          "2",
          "$permissions.owners"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "permissions": {
        "$push": "$permissions"
      },
      "owner": {
        "$push": "$owner"
      }
    }
  },
  {
    "$set": {
      "owner": {
        "$in": [
          true,
          "$owner"
        ]
      }
    }
  }
])

Example here

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!