0

我想知道在 MongoDB 中查询单个嵌入式文档时是否有办法获取单个对象而不是数组

我有嵌入用户的

{
 groupname: "Admins",
 users: [
    { 
        email: bob@google.com, 
        first_name: 'bob'
    },
    {...},
    {...} // multiple embedded users
 ]
}

我可以使用此查询从组中查询单个用户

db.groups.find({'users.email' => bob@google.com}, {'users.$' => 1})

但它给了我一个带有 1 个用户初始化的“用户”数组

{
 groupname: "Admins",
 users: [
    { 
        email: bob@google.com, 
        first_name: 'bob'
    }
 ]
}

然后我必须选择数组中的第一个元素,

users[0] 

没有问题,但是我只需要在我的应用程序中编写更多代码,更好的方法应该是

user (-s)

所以我可以查询

user.first_name

如果有人知道方法让我知道

4

2 回答 2

1
You can use findOne as it returns a single document, where find returns a cursor.

>user =  db.groups.findOne({'users.email' : bob@google.com}, {'users.$' => 1})
>user.first_name
于 2014-08-13T18:49:40.613 回答
0

根据您使用的驱动程序不推荐使用 findOne,您应该使用find().limit(1).next(function(err, doc){})

http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOne

于 2016-10-16T16:42:49.157 回答