查询嵌入文档 [英] Query embedded documents

查看:60
本文介绍了查询嵌入文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将创建一个这样的架构:

<预><代码>[{用户名:法比奥",密码:xxx",角色: [{角色名称:管理员",isVip: 真},{角色名称:经理",isVip: 真}]},{用户名:马可",密码: "yyy",角色: [{角色名称:经理",isVip: 真}]},{用户名:pippo",密码: "...",角色: [{角色名称:猴子",isVip: 假}]}]

现在我想列出我的应用中所有可用的角色,从用户集合开始.

我想到了一个 SELECT DISTINCT rolename FROM ... SQL 语句.

我想得到类似 {"administrator","manager","monkey"} 的结果.

  1. 有可能吗?
  2. 我可以执行什么查询?我想:

    db.users.find({ "roles.rolename": { $exists : true }});

    但这会找到所有用户,而不是所有角色.

  3. 好用吗?还是创建另一个角色"集合并保留一组 ObjectId 更好?

  4. 我正在使用 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"} .

  1. Is it possible?
  2. What query may I execute? I tought about:

    db.users.find({ "roles.rolename": { $exists : true }});

    But that will find all users, not all roles.

  3. Is it good? Or is it better creating another collection "roles" and keep an array of ObjectIds?

  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆