Search code examples
couchbasesql++spring-data-couchbase

how to retrieve the child of the parent in n1ql query


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

SELECT ARRAY {s.name,s.id} FOR s IN t.countryDetails.stateInfo END AS stateDetails
FROM test AS t 
WHERE t.type = "countries" and t.countryDetails.name = 'US';

this is the actual json document i am trying to query:

{
   "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 country state details of US only:

[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ] 

Solution

  • If you your ConutryDetails has single entry per country use the following

    SELECT FIRST s.stateInfo FOR IN t.countryDetails WHEN s.name = "US" END AS stateDetails
    FROM test AS t 
    WHERE t.type = "countries" 
          AND ANY v IN t.countryDetails SATISFIES v.name = 'US' END;
    

    OR

    SELECT cd.stateInfo AS stateDetails
    FROM test AS t
    UNNEST t.countryDetails AS cd
    WHERE t.type = "countries" AND cd.name = 'US';