Is there any way to query inside this struture by the object keys of roles
?
interface UsersModel{
_id: string;
email: string;
roles: { [key: string]: RolesType[] };
}
For now I get the data into users
like:
roles: {
$ne: null
}
and then
const finalResult = users.filter(u => Object.keys(u.roles).includes('objectKeyIwant'));
Can this be done on the mongodb side and avoid getting all the data then filter it?
Data examples: The user collection is like this:
{
_id: '610baff85c071a2bd59dc84f',
email: 'some@email.com',
roles : {
"shop1" : [
"shop_stock_manager"
],
"shop2" : [
"shop_admin",
"shop_stock_manager"
]
}
}
And I want to get all the users that have any role in shop2
.
use this
db.collection.find({"roles.shop2":{$ne:[]}})