I cannot filter items that only have a specific role:
When I try to filter only the element with rol ROL_CONTADOR return all elements of items, but the second element in items, not should filter.
db.menu.find({ "items": { "$elemMatch": { "roles": {$in: ["ROL_ARTICULOS"] } } } })
{
"label": "Reportes",
"icon": "list",
"items": [
{
"label": "Cajas",
"link": "/articulos",
"icon": "check_circle_outline",
"roles": [
"SYSADMIN",
"ROL_CONTADOR"
]
},
{
"label": "Ventas",
"link": "/articulos",
"icon": "check_circle_outline",
"roles": [
"SYSADMIN",
"ROL_VENTAS"
]
}
]
},
{
"label": "Facturas",
"icon": "list",
"items": [
{
"label": "Administración",
"link": "/articulos",
"icon": "check_circle_outline",
"roles": [
"SYSADMIN",
"ROL_FACTURAS"
]
}
]
}
I have to use the $in clause because a user can have multiple roles, but I need only to get the items that fulfill the role
db.collection.aggregate([ { $match: { "items.roles": { $in: [ "ROL_CONTADOR", "ROL_FACTURAS", "ROL_VENTAS"] } } }, { $set: { items: { $filter: { input: "$items", cond: { $or: [ { $in: [ "ROL_CONTADOR", "$$this.roles"] }, { $in: [ "ROL_FACTURAS", "$$this.roles"] }, { $in: [ "ROL_VENTAS", "$$this.roles"] }] } } } } }])