Search code examples
sql++spring-data-couchbase

how can i retrieve all the childrens by n1ql query


I am planning to retrieve the child elements all the parent, How can i retrieve it, being inside the array of array objects.

SELECT sd.* 
FROM test AS t
UNNEST stateDetails AS sd;
{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}

I am expecting the following output to bring out the state details of all the countries with their respective country Name

        [
            {
               "countryName":"US",
               "name":"Florida",
               "id":"1212"
            },
            {
               "countryName":"US",
               "name":"NewYork",
               "id":"1214"
            },
            {
               "countryName":"France",
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "countryName":"France",
               "name":"Brittany",
               "id":"5214"
            }
         ]  

Solution

  • Use double UNNEST and project what you need

    SELECT cd.name AS countryName, sd.name, sd.id
    FROM test AS t
    UNNEST t.countryDetails AS cd
    UNNEST cd.stateInfo AS sd
    WHERE t.type = "countries";