Search code examples
couchbasesql++

Couchbase N1QL query to select value from object array


What's the correct way to select a value from an array of objects?

Would like to retrieve a distinct list of the comments.

[
  "comment 1",
  "comment 2",
  "comment 3",
  "comment 4"
]

Current N1QL query

SELECT links[*].comment FROM `my-db`
WHERE type = "links" AND ANY l IN links SATISFIES l.comment IS NOT MISSING END

Results

[
  {
    "comment": [
      "comment 1"
    ]
  },
  {
    "comment": [
      "comment 1",
      "comment 2"
    ]
  },
  {
    "comment": [
      "comment 3",
      "comment 4"
    ]
  }
]

Given a series of documents that contain a comment field:

{
  "type": "links",
  "links": [
    {
      "comment": "comment 1"
    }
  ]
}

{
  "type": "links",
  "links": [
    {
      "comment": "comment 1"
    },
    {
      "comment": "comment 2"
    }
  ]
}

{
  "type": "links",
  "links": [
    {
      "comment": "comment 3"
    },
    {
      "comment": "comment 4"
    }
  ]
}

Solution

  • Use UNNEST

    SELECT DISTINCT RAW l.comment 
    FROM `my-db` AS m
    UNNEST m.links AS l
    WHERE m.type = "links" AND l.comment IS NOT NULL;
    

    OR

    If data set is not too large.
    
    SELECT RAW  ARRAY_DISTINCT(ARRAY_FLATTEN(ARRAY_AGG(m.links[*].comment) ,2))
    FROM `my-db` AS m
    WHERE m.type = "links";