1
0
Fork 0
arangodb/Documentation/Books/Users/AqlOperations/Insert.mdpp

86 lines
2.7 KiB
Plaintext

!CHAPTER INSERT
The *INSERT* keyword can be used to insert new documents into a collection. On a
single server, an insert operation is executed transactionally in an all-or-nothing
fashion. For sharded collections, the entire insert operation is not transactional.
Each *INSERT* operation is restricted to a single collection, and the
[collection name](../Glossary/README.md#collection-name) must not be dynamic.
Only a single *INSERT* statement per collection is allowed per AQL query, and
it cannot be followed by read operations that access the same collection, by
traversal operations, or AQL functions that can read documents.
The syntax for an insert operation is:
```
INSERT document IN collection options
```
**Note**: The *INTO* keyword is also allowed in the place of *IN*.
*collection* must contain the name of the collection into which the documents should
be inserted. *document* is the document to be inserted, and it may or may not contain
a *_key* attribute. If no *_key* attribute is provided, ArangoDB will auto-generate
a value for *_key* value. Inserting a document will also auto-generate a document
revision number for the document.
```
FOR i IN 1..100
INSERT { value: i } IN numbers
```
When inserting into an [edge collection](../Glossary/README.md#edge-collection), it is mandatory to specify the attributes
*_from* and *_to* in document:
```
FOR u IN users
FOR p IN products
FILTER u._key == p.recommendedBy
INSERT { _from: u._id, _to: p._id } IN recommendations
```
!SUBSECTION Setting query options
*options* can be used to suppress query errors that may occur when violating unique
key constraints:
```
FOR i IN 1..1000
INSERT { _key: CONCAT('test', i), name: "test" } WITH { foobar: true } IN users OPTIONS { ignoreErrors: true }
```
To make sure data are durable when an insert query returns, there is the *waitForSync*
query option:
```
FOR i IN 1..1000
INSERT { _key: CONCAT('test', i), name: "test" } WITH { foobar: true } IN users OPTIONS { waitForSync: true }
```
!SUBSECTION Returning the inserted documents
The inserted documents can also be returned by the query. In this case, the `INSERT`
statement can be a `RETURN` statement (intermediate `LET` statements are allowed, too).
To refer to the inserted documents, the `INSERT` statement introduces a pseudo-value
named `NEW`.
The documents contained in `NEW` will contain all attributes, even those auto-generated by
the database (e.g. `_id`, `_key`, `_rev`, `_from`, and `_to`).
```
INSERT document IN collection options RETURN NEW
```
Following is an example using a variable named `inserted` to return the inserted
documents. For each inserted document, the document key is returned:
```
FOR i IN 1..100
INSERT { value: i }
LET inserted = NEW
RETURN inserted._key
```