I am trying to select all users which references a group that references a permission that has "valid" set to true (possibly multiple). To achieve this I am planning to use an aggregation with a lookup.
db={
"users": [
{
"_id": "1",
"groups": [
"2"
]
},
{
"_id": "2",
"groups": [
"1"
]
}
],
"group": [
{
"_id": "1",
"permissions": [
"12",
"3"
]
},
{
"_id": "2",
"permissions": [
"3",
"2"
]
}
],
"permission": [
{
"_id": "12",
"valid": true
},
{
"_id": "3",
"valid": true
},
{
"_id": "2",
"valid": true
}
]
}
I can't think of an efficient/simple way to do this.
I have 2 ideas:
Any ideas or inputs on this?
$unwind in lookup as localFields,group field with permissions response because it is not needed in next stagedb.users.aggregate([
{
$lookup: {
from: "group",
localField: "groups",
foreignField: "_id",
as: "group"
}
},
{
$lookup: {
from: "permission",
localField: "group.permissions",
foreignField: "_id",
as: "group"
}
},
{ $match: { "group.valid": true } },
{ $unset: "group" }
])