简体   繁体   中英

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

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

{
 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){})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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