Reputation: 95
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 !
Upvotes: 1
Views: 2050
Reputation: 43245
You would need to use $elemMatch :
http://docs.mongodb.org/manual/reference/projection/elemMatch/
db.testpymongo.find( { "Project": { $elemMatch: { "pname": "project1" } } } )
Upvotes: 1