Skip to main content

Replace documents

ArangoDB's official AQL docs for REPLACE can be found here

tip

We are going to updating documents to cover the basics of replace.

  • To avoid polluting the travel dataset we created a scratch collection here
  • We created a few documents in the scratch collection using insert and AQL here
  • We will be using the ArangoDB Query Interface to run the queries, see instructions to get to the interface here

Setup

  1. 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
  2. Now that the document is added we can demonstrate all the operations on the test document

Replace using a key

  1. 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
  2. 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

  1. 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]
  2. Compare the results of the upsert and repsert to see the difference in behavior

Repsert without using a key

danger

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.

 
Help us improve

Anything unclear or buggy in this tutorial? Provide Feedback