title: Limit array size Couchbase update query
body: <p>i have got a couchbase n1ql update query:</p>
  
  <pre><code>UPDATE `store` document USE KEYS "test" 
  SET document = ARRAY_APPEND(ARRAY_REMOVE(document, "c"), "c")
  </code></pre>
  
  <p>this update will remove all occurences of the given "c" from the document and is then appending it to the end.</p>
  
  <p>now i also want to limit the resulting array to a specific length, so the result never exeeds something like 50 array elements or so</p>
  
  <p>since array slicing wont give a propper result, when the length of the array is less than the given slice, there is some more logic required.</p>
  
  <p>i have tried the following:</p>
  
  <pre><code>UPDATE `store` document USE KEYS "test" 
  LET temp = ARRAY_APPEND(ARRAY_REMOVE(document, "c"), "c")
  SET document = temp[-least(ARRAY_LENGTH(temp), 50):]
  </code></pre>
  
  <p>which fails, because "LET" is not part of the UPDATE syntax</p>
  
  <p>is there any way to achieve limiting the stored array in size by using a single update statement?</p>
  
  <p>EDIT:
  with the selected answer and an additional case for new documents, i came up with this final solution:</p>
  
  <pre><code>MERGE INTO `store` document
  USING (SELECT NULL) s ON KEY "test_x"
  WHEN MATCHED THEN 
      UPDATE SET document = ARRAY_REVERSE(
          ARRAY v FOR i:v IN ARRAY_REVERSE(
              ARRAY_APPEND(ARRAY_REMOVE(document, "i"), "i")
          ) WHEN i &lt; 3 END
      )
  WHEN NOT MATCHED THEN 
      INSERT ["i"]
  RETURNING *
  </code></pre>