Replace documents
ArangoDB's official AQL docs for REPLACE can be found here
We are going to updating documents to cover the basics of replace.
Setup
Lets create a document first which we can use to learn about all the supported UPDATE operations update,replace,repset,upsert:
insert {'_key':'test-replace','field1': 'foo','field2': 'bar', 'field3':'baz'} into scratch return NEW
Now that the document is added we can demonstrate all the operations on the test document
Replace using a key
You can replace a document by directly specifying a key and the fields:
replace {_key: 'test-replace'} WITH {'field6': "foo-updated", 'field7': 'new-field'} IN scratch RETURN NEW
or
replace {_key: 'test-replace', 'field6': "foo-updated", 'field7': 'new-field'} IN scratch RETURN NEW
Replace will completely replace the contents of the document with the provided document. You should see the following result:
[
{
"_key": "test-replace",
"_id": "scratch/test-replace",
"_rev": "_gdr8uVW--A",
"field6": "foo-updated",
"field7": "new-field"
}
]info- Replace operations require a key
- As expected a REPLACE completely overwrites the document with the provided data
Repsert using a key
Repserts are used to insert-or-replace, so a document will be inserted if one doesnt exist otherwise it will be replaced.
upsert {_key: 'test-repsert'}
insert {_key: 'test-repsert','field1': "foo", 'field2': 'bar','field3': 'baz'}
replace {'field1': 'foo-updated','field4': 'new-field'} IN scratch
return [OLD, NEW]Compare the results of the upsert and repsert to see the difference in behavior
Repsert without using a key
Repsert operations can be run without specifying a _key in the upsertExpression, but the behavior is undefined if more than one document matches the upsert operation
Per the official documentation here:
In case at least one document in collection matches the searchExpression, it will be updated using the updateExpression. When more than one document in the collection matches the searchExpression, it is undefined which of the matching documents will be updated. It is therefore often sensible to make sure by other means (such as unique indexes, application logic etc.) that at most one document matches searchExpression.
Anything unclear or buggy in this tutorial? Provide Feedback