1

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 !

1 Answer 1

1

You would need to use $elemMatch :

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

db.testpymongo.find(  { "Project": { $elemMatch: { "pname": "project1"  } } } )
Sign up to request clarification or add additional context in comments.

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.