Search code examples
couchbasesql++

Nest an Object returned by query as an array of size one


I'm currently trying to query a specific object from an array. However, the result of the query is returning a single object as opposed to an array of size one (with the one object populating the array).

My query:

SELECT meta(bn).id as _ID, meta(bn).cas as _CAS, bn.name
    FIRST t FOR t IN properties WHEN t.id = "1111" END as property
FROM bucket-name as bn
WHERE ANY t IN attributes SATISFIES t.id = "1111" END

result:

[
{
    "_CAS": 0000,
    "_ID": "1111",
    "name": "my name",
    "property": {
        "id": "1111",
        "name": "my property name"
    }
}
]

What I would rather be getting is. It's almost exactly identical, except "property" is now an array

[
{
    "_CAS": 0000,
    "_ID": "1111",
    "name": "my name",
    "property": [
        {
            "id": "1111",
            "name": "my property name"
        }
    ]
}
]

Solution

  • Change FIRST To ARRAY https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/collectionops.html When used FIRST the loop stops when first element satisfied and returns the element. When used ARRAY the loop continue till end and all qualified elements are returns as ARRAY (i.e. list)

    SELECT meta(bn).id as _ID, meta(bn).cas as _CAS, bn.name
        ARRAY t FOR t IN properties WHEN t.id = "1111" END AS property
    FROM `bucket-name` as bn
    WHERE ANY t IN attributes SATISFIES t.id = "1111" END;