1

I have a data structure as following:

object1.array1[object2.array2[]]

I want to remove array2 from object2 or delete all array elements.

Is there a solution for this using AQL-Query?

1 Answer 1

2

Demo document:

{
  "foo": [
    {"x": [1,2,3], "y": [4,5,6], "z": [7,8,9] },
    {"hello": "world" }
  ],
  "bar": true,
  "_key": "0"
}

To remove foo[0].y ([4,5,6]) with AQL, here is a somewhat generic solution:

LET attr = "foo"  // target top-level attribute
LET i = 0         // positive or negative index of target array element
LET subattr = "y" // sub-attribute to remove

LET doc = DOCUMENT("test/0")

LET before = SLICE(doc[attr], 0, i)              // array elements before target
LET middle = UNSET(doc[attr][i], subattr)        // remove sub-attribute from target element
LET after = i == -1 ? [] : SLICE(doc[attr], i+1) // elements after target
LET combined = APPEND(APPEND(before, middle), after)

UPDATE doc WITH { [attr]: combined } IN test
RETURN {NEW, OLD}

To remove "world" instead, simply change it to LET i = 1 and LET subattr = "hello".

Sign up to request clarification or add additional context in comments.

2 Comments

Could you tell me, what in details happens here? LET after = i == -1 ? [] : SLICE(doc[attr], i+1) // elements after target
As long as i is a positive, you can simplify it to LET after = SLICE(doc[attr], i+1). It gets the array elements from foo after i. I wanted it to work for negative values too, e.g.LET i = -1 to target the last element of foo (foo[-1].hello). The problem is that i+1 = -1+1 = 0, resulting in SLICE(doc[attr], 0), which would return all elements of foo. Therefore, I made use of the ternary operator ? : (cutt.ly/eepqE0M): if i equals -1 then return empty array (there are no elements after the last one), otherwise do usual slicing: i == -1 ? [] : SLICE(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.