查询嵌入文档 [英] Query embedded documents
问题描述
我将创建一个这样的架构:
<预><代码>[{用户名:法比奥",密码:xxx",角色: [{角色名称:管理员",isVip: 真},{角色名称:经理",isVip: 真}]},{用户名:马可",密码: "yyy",角色: [{角色名称:经理",isVip: 真}]},{用户名:pippo",密码: "...",角色: [{角色名称:猴子",isVip: 假}]}]现在我想列出我的应用中所有可用的角色,从用户集合开始.
我想到了一个 SELECT DISTINCT rolename FROM ...
SQL 语句.
我想得到类似 {"administrator","manager","monkey"}
的结果.
- 有可能吗?
我可以执行什么查询?我想:
db.users.find({ "roles.rolename": { $exists : true }});
但这会找到所有用户,而不是所有角色.
好用吗?还是创建另一个角色"集合并保留一组 ObjectId 更好?
我正在使用 Mongoose(用于 nodejs 的 mongodb),所以我的查询必须为此做好准备.
您可以使用 distinct() 命令来查找唯一值:
<代码>>db.users.distinct('roles.rolename')[管理员"、经理"、猴子"]
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:
> db.users.distinct('roles.rolename')
[ "administrator", "manager", "monkey" ]
这篇关于查询嵌入文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!