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
}
}
}
}
But it always ends up being false. Any ideas?
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