简体   繁体   English

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

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

I wonder if there is a way to get a single object instead of an array when querying for a single embedded document in MongoDB 我想知道在MongoDB中查询单个嵌入式文档时是否有办法获取单个对象而不是数组

I have Groups with embedded Users 我有具有嵌入式用户的 网上论坛

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

I can query a single user from a group with this query 我可以使用此查询从组中查询单个用户

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

but it gives me a 'users' array with 1 user init 但这给了我一个带有1个用户init的'users' 数组

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

then I have to select the first element in the array, 然后我必须选择数组中的第一个元素,

users[0] 

there is no problem with it, but then i just have to write more code in my application, the better way should be 它没有问题,但是那我只需要在我的应用程序中编写更多代码,更好的方法应该是

user (-s)

so I can query 所以我可以查询

user.first_name

if someone knows a way let me know 如果有人知道让我知道

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

Depending from the driver you are using findOne is deprecated, you should use find().limit(1).next(function(err, doc){}) 根据不赞成使用findOne的驱动程序,应使用find()。limit(1).next(function(err,doc){})

http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOne 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