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}
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 totrue
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
}
}
])