0
{
"_id" : ObjectId("5b4d815ad85250f4e502d142"),
"company_Name" : "Rishabh Instruments",
"spaces" : [ 
    {
        "_id" : "11",
        "name" : "Trishala",
        "spaces" : [ 
            {
                "_id" : "111",
                "name" : "ESL"
            }, 
            {
                "_id" : "112",
                "name" : "IS"
            }
        ]
    }, 
    {
        "_id" : "12",
        "name" : "Riddhi",
        "spaces" : [ 
            {}
        ]
    }, 
    {
        "name" : "XYZ",
        "spaces" : [ 
            {}
        ]
    }
]

}

This is my Document structure in Mongo DB and it may have the sub documents upto N th level so for now I want to access the document named with ESL and IS. so how can i do that i am able to go upto 2nd level with below query so

    db.space.aggregate([
    {$match: {company_Name: 'Rishabh Instruments'}},
    {$unwind: '$spaces'},
    {$match: {'spaces.name': 'Trishala'}}
   // {$unwind: '$spaces'},
   // {$match: {'spaces.name': 'ESL'}}

])

but if i uncomment those two lines then it doesn't return any thing so can anyone guide me or give any hint.

  • 2
    Possible duplicate of [$filter upto 3 nested level in mongodb](https://stackoverflow.com/questions/51332387/filter-upto-3-nested-level-in-mongodb) – Ashh Jul 17 '18 at 07:47
  • Possible duplicate of [$filter upto 2 nested level in mongodb](https://stackoverflow.com/questions/51330010/aggregation-and-filter-not-working/51330135#51330135) – Ashh Jul 17 '18 at 07:49
  • Within `$match` you can use regular query syntax. Can't you just build up from that? See e.g.: https://docs.mongodb.com/manual/tutorial/query-array-of-documents/ – Arnold Schrijver Jul 17 '18 at 08:00
  • Can you provide us a sample output, as to what do you expect the response structure should be? – Subhashree Pradhan Jul 17 '18 at 08:38
  • expecting output like { "_id" : "111", "name" : "ESL" }, { "_id" : "112", "name" : "IS" } – Vishal Gadge Jul 17 '18 at 08:39

2 Answers2

0

I tried the below solution and its working as expected i can go to N th level by chaining the key as in my case key is spaces

db.space.aggregate([
    {$match: {company_Name: 'Rishabh Instruments'}},
    {$unwind: '$spaces'},
    {$match: {'spaces.name': 'Trishala'}},
    {$unwind: '$spaces.spaces'},
    {$match: {'spaces.spaces.name': 'ESL'}}

]) 
0

Try this aggregate query with projection to match the sample output you had provided :

db.space.aggregate([
    {$match: {company_Name: 'Rishabh Instruments'}},
    {$unwind: '$spaces'},
    {$match: {'spaces.name': 'Trishala'}},
    {$unwind: '$spaces.spaces'},
    {$match: {$or : [{'spaces.spaces.name': 'ESL'},{'spaces.spaces.name': 'IS'}]}},
    {$project : {_id : 0, _id :'$spaces.spaces._id', name:'$spaces.spaces.name'}}
])

Output :

{ "_id" : "111", "name" : "ESL" }
{ "_id" : "112", "name" : "IS" }