Scoping FOR loop - to prevent duplicate INSERT

19 views
Skip to first unread message

Klaas van der Molen

unread,
May 16, 2025, 6:41:28 AMMay 16
to ArangoDB
Hi,

The query below inserts the object {title: "c"} twice in collection_2.

However I want only one insert for the second collection.

The question is how to scope the FOR loop in this case? 
Brackets are not accepted.

LET array = [{title: "a"},{title: "b"}]
FOR item IN array
    INSERT item INTO collection_1
INSERT {title: "c"} INTO collection_2

Many thanks!
Klaas van der Molen

Wilfried Gösgens

unread,
May 16, 2025, 6:43:11 AMMay 16
to ArangoDB
Hi,
the only way AQL offers to break the scope is to use a sub-query, which will then be executed before the main query.

Michael Hackstein

unread,
May 16, 2025, 7:47:45 AMMay 16
to aran...@googlegroups.com
Hi,

For this particular query there are actually two more possibilities:

LET array = [{title: "a"},{title: "b"}]
FOR item IN array
    INSERT item INTO collection_1
INSERT {title: "c"} INTO collection_2

Could run as:

INSERT {title: "c"} INTO collection_2
LET array = [{title: "a"},{title: "b"}]
FOR item IN array
    INSERT item INTO collection_1

This way the second INSERT statement is bore the Loop over array.
AQL is not whitespace sensitive for scopes

Which means your query is actually:


LET array = [{title: "a"},{title: "b"}]
FOR item IN array
    INSERT item INTO collection_1
    INSERT {title: "c"} INTO collection_2

The second insert is within the loop.


The other alternative to a subquery would be a COLLECT with constant condition:

LET array = [{title: "a"},{title: "b"}]
FOR item IN array
    INSERT item INTO collection_1
COLLECT x = 1 /* This groups all outputs of the former for loop. AS the grouping is done on a constant, we will end up with a single Group */
INSERT {title: "c"} INTO collection_2

Best
Michael


-- 
You received this message because you are subscribed to the Google Groups "ArangoDB" group.
To unsubscribe from this group and stop receiving emails from it, send an email to arangodb+u...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/arangodb/e5f06d36-b31a-461b-aa90-5bfc831c1283n%40googlegroups.com.

Simran Spiller

unread,
Aug 28, 2025, 5:16:14 AM (11 days ago) Aug 28
to ArangoDB
Instead of grouping by a constant, you can also apply a LIMIT for the same effect:

LET array = [{title: "a"},{title: "b"}]
FOR item IN array
    INSERT item INTO collection_1
    LIMI1
    INSERT {title: "c"} INTO collection_2

Reply all
Reply to author
Forward
0 new messages