繁体   English   中英

mongodb查找单个嵌入式文档作为对象而不是数组

[英]mongodb find single embedded document as an object not as an array

我想知道在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个用户init的'users' 数组

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

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

users[0] 

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

user (-s)

所以我可以查询

user.first_name

如果有人知道让我知道

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

根据不赞成使用findOne的驱动程序,应使用find()。limit(1).next(function(err,doc){})

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM