Search code examples
couchbasesql++

N1QL Check if the array contains id


I have a document called

player::id

for each player. Where id is the player's id (auto-incremented).

How can I run search operations on the array below such as checking the id's or count? This array is stored in a player's save document.

"inventory": {
    "0": {
      "count": 1,
      "id": 6
    },
    "1": {
      "count": 1,
      "id": 13
    },
    "2": {
      "count": 1,
      "id": 142
    },
    "3": {
      "count": 1,
      "id": 144
    }
},


Solution

  • There is no ARRAY in the object you have posted.

    if you want search id 13 is present in the document and get the corresponding count you can use OBJECT_PAIRS() function which convert dynamic object into ARRAY described https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/objectfun.html

    SELECT op.val.id, op.val.count, op.name AS pos
    FROM default AS d
    UNNEST OBJECT_PAIRS(d.inventory) AS op
    WHERE op.val.id = 13
    

    OR

    SELECT d.*
    FROM default AS d
    WHERE ANY op IN OBJECT_PAIRS(d.inventory) SATISFIES op.val.id = 13 END;