Query to extract single record from nested document

84 views
Skip to first unread message

vishin

unread,
Apr 12, 2011, 3:23:50 AM4/12/11
to mongodb-user
Hi,


I am working on a nested document using mongoDB. I am facing a problem
while retrieving a particular
item from a nested document

My document looks like this :

> db.mycollection.find()
{ "_id" : ObjectId("4da3f7fe0707c4baa12cafbe"),
"formname" : "myform",
"records" : [
{
"feild1" : "feild1val",
"feild2" : "feildval2"
},
{
"feild1" : "feild1valn",
"feild2" : "feildval2n"
}
] }


I need to retrieve the value

{ "feild1" : "feild1val",
"feild2" : "feildval2"
},

that is the first element in the key 'records'
Is this possible ?

I tried this query -
db.mycollection.find({"records.feild1":"feild1val"}). But it is
returning the whole items in the "records" field.

Anything is appreciated.

Thanks,
Vishin

Kyle Banker

unread,
Apr 12, 2011, 9:37:48 AM4/12/11
to mongod...@googlegroups.com
That's the correct behavior. A query always return the entire document.

You can do a project if you want:
db.mycollection.find({"records.feild1":"feild1val"}, {"records.0": 1})

But if you need to query on the record attributes frequently, you may
want to place them in their own collection.

> --
> You received this message because you are subscribed to the Google Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.
>
>

axlfu

unread,
Apr 12, 2011, 11:20:51 AM4/12/11
to mongodb-user
cannot use db.mycollection.find({"records.feild1":"feild1val"},
{"records.0": 1}) to return single record....
what dose doing a project mean?

On Apr 12, 1:37 pm, Kyle Banker <k...@10gen.com> wrote:
> That's the correct behavior. A query always return the entire document.
>
> You can do a project if you want:
> db.mycollection.find({"records.feild1":"feild1val"}, {"records.0": 1})
>
> But if you need to query on the record attributes frequently, you may
> want to place them in their own collection.
>

Kyle Banker

unread,
Apr 13, 2011, 11:35:34 AM4/13/11
to mongod...@googlegroups.com
Sorry. I meant "projection." Try the $slice operator:

db.mycollection.find({"records.feild1":"feild1val"}, {"records": {$slice: 1}})

Reply all
Reply to author
Forward
0 new messages