Search code examples
couchbasesql++

How to sort inner array of document which is retrieved by using document ID


SELECT * from bucket b WHERE meta().id = 'PROFILE_LIST'

Above query gives below result, but in addition I need the inner array matchingProfile_ should come in sorted order of createdDate. Is it possible? if yes, What changes I have to make for this query to achieve the same?

[
   {
    "matchingProfile_": [
            {
              "createdDate": "2020-09-26T02:30:00",
              "contactDetails_": {
                "address_": {
                  "addressLine1_": "",
                  "addressLine2_": "",
                  "city_": ""
                 }
            },
            {
              "createdDate": "2020-09-27T02:30:00",
              "contactDetails_": {
                "address_": {
                  "addressLine1_": "",
                  "addressLine2_": "",
                  "city_": ""
                 }
            }
    ]
   }
]

Solution

  • Use subquery expression preserve whole document structure and sort array on desired way (even use complete SQL functionality)

    SELECT b.*, 
          (SELECT RAW mp 
           FROM b.matchingProfile_ AS mp 
           ORDER BY mp.createdDate) AS matchingProfile_
    FROM bucket AS b USE KEYS 'PROFILE_LIST';