0

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: [email protected], 
        first_name: 'bob'
    },
    {...},
    {...} // multiple embedded users
 ]
}

I can query a single user from a group with this query

db.groups.find({'users.email' => [email protected]}, {'users.$' => 1})

but it gives me a 'users' array with 1 user init

{
 groupname: "Admins",
 users: [
    { 
        email: [email protected], 
        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

0

2 Answers 2

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

>user =  db.groups.findOne({'users.email' : [email protected]}, {'users.$' => 1})
>user.first_name
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.