Find a single field from a nested Array in MongoDB -


here have sample nested array. have problem writing proper queries on collection nested.

{ "productuuid" : "craft001", "providers": [ {   "provideruuid": "prov001",   "orgs": [     {       "orguuid": "org001",       "location": {         "buildings": [           {             "buildinguuid": "sit001",             "floors": [               {                 "flooruuid": "grndflr",                 "assets": [ ],                 "agents": [ ],                 "users": [ ]               },               {                 "flooruuid": "1stflr",                 "assets": [ ],                 "agents": [ ],                 "users": [ ]               }             ]           },           {             "buildinguuid": "ist001",             "floors": [ ]           }         ]       }     },     {       "orguuid": "org002",       "location": {         "buildings": [ ]       }     }   ] }, {   "provideruuid": "prov002",   "orgs": [ ] } ] } 

question in simple words, "1. orguuids fall under provideruuid: "prov001"". similarly, "2. flooruuids "buildinguuid": "sit001"".

if can me 1st ques, hope can solve 2nd ques myself.

mongo aggregation use finding nested documents. first unwind providers array use match match provideruuid given prov001 used project orguuid , aggregation query :

db.collectionname.aggregate({"$unwind":"$providers"},                             {"$match":{"providers.provideruuid":"prov001"}},                             {"$project":{"orguuid":"$providers.orgs.orguuid"}},                             {"$unwind":"$orguuid"},                             {"$project":{"_id":0,"orguuid":1}}                            ).pretty() 

this returns orguuid in array.

if use $elemmacth operator having it's own limitation

the $elemmatch operator matches documents contain array field @ least 1 element matches specified query criteria.

elemmatch query :

 db.collectionname.find({"providers":{"$elemmatch":{"provideruuid":"prov001"}}},                         {"providers.$.provideruuid.orgs.orguuid":1}).pretty() 

it returns whole matching providers array.

i hope find out "2" question query yourself, if having trouble finding "2" query post "2" query also. try find out second query answer :)


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -