Mongodb python syntax to get array value . -


so please gentle

have mongo doc :

{ "institute" : "ucambridge",     "project" : [ #array of projects                {"sample":[ #array of samples                       { "workflow" : "abc", "owner" : "peter" }                ]                "pname":"project1",                 "dir" : "c drive"                }                 ] } 

i aware having nested loops in mongo isn't great idea , way data being handed me.

trying loop on projects , extract project name, on python server.

so cursor :

u = mongo.db.testpymongo.find( )

can institute :

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

can project :

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 access pname variable cursor ?

i have tried :

1.print x["project:pname"] # 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 using attributes in find() function return part of document ?

i.e : ?

d = mongo.db.testpymongo.find( {"institute":"ucambridge", "project.pname": "project 1" } )

thank !

you need use $elemmatch :

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

db.testpymongo.find(  { "project": { $elemmatch: { "pname": "project1"  } } } ) 

Comments