Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

so please be gentle

Have a mongo doc like this :

{ "Institute" : "Ucambridge",

   "Project" : [ #array of projects
               {"Sample":[ #array of samples
                      { "workflow" : "abc", "owner" : "peter" }
               ]
               "pname":"project1",
                "dir" : "C drive"
               }

               ]
}

I am aware that having nested loops in mongo isn't a great idea , however this is the way the data is being handed to me.

Trying to loop over all my projects and extract the project name, on my python server.

so get cursor :

u = mongo.db.testpymongo.find( )

Can get Institute by :

for x in u : 
print x["Institute"]

Can get project by :

for x in u : 
    print x["Project"]

which returns :

[{u'Sample':[{u'workflow:':u'wf', u'owner':u'peter'} ] u'pname':u'project1 ', u'dir:u'C drive'}]

but , how do i get access to just my pname variable from the cursor ?

i have tried :

1.print x["Project:pname"] # does not work

2.print x["Project":"pname"] # gives unhashable type error 

3.print x["pname"]  # gives Key error 

4.print x["Project"].["pname"] # gives syntax error

5.print x["Project.pname"] # gives key error 

Should i be using attributes in the find() function to only return part of the document ?

i.e : like so ?

d = mongo.db.testpymongo.find( {"Institute":"UCambridge", "Project.pname": "project 1" } )

Thank you !

share|improve this question
up vote 1 down vote accepted

You would need to use $elemMatch :

http://docs.mongodb.org/manual/reference/projection/elemMatch/

db.testpymongo.find(  { "Project": { $elemMatch: { "pname": "project1"  } } } )
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.