I’m going to create a schema like this:
[
{
username: "fabio",
password: "xxx",
roles: [
{
rolename: "administrator",
isVip: true
},
{
rolename: "manager",
isVip: true
}
]
},
{
username: "marco",
password: "yyy",
roles: [
{
rolename: "manager",
isVip: true
}
]
},
{
username: "pippo",
password: "...",
roles: [
{
rolename: "monkey",
isVip: false
}
]
}
]
Now I want to list all roles available in my app, starting from the users collection.
I think about a SELECT DISTINCT rolename FROM ... SQL statement.
I’d like to get a result like {"administrator","manager","monkey"} .
- Is it possible?
-
What query may I execute? I tought about:
db.users.find({ “roles.rolename”: { $exists : true }});
But that will find all users, not all roles.
-
Is it good? Or is it better creating another collection “roles” and keep an array of ObjectIds?
-
I am using Mongoose (mongodb for nodejs) so my query has to be ready for that.
You can use the distinct() command to find the unique values: