Updating data

Once a document is stored in a RethinkDB table, it can be changed using the update() command. This command accepts a JSON document or ReQL expression as input and returns the number of updated documents.

Updating existing attributes

Updating a document can alter one or more attributes already present within the document itself, or can add a new attribute. Let's pretend we made a mistake inserting Amy's year of birth and we want to change the value from 1998 to 1997; we can update the related document using the following query:

r.table('people').get('f1664276-1aad-4998-8240-410a82883115').update({"yearOfBirth": 1997})

First, we get the correct document using its primary key. Then we call the update() command, passing it a JSON document that contains the changes. In this case, the change is as follows:

({"yearOfBirth": 1997}

If we now query the database searching for Amy's document, we can see that year of birth has, in fact, been updated correctly:

Updating existing attributes

Note

The query used in the previous screenshot uses the filter() command to access the document instead of using the primary key for demonstration purposes; however, you should always use the primary key if possible as using filter() requires a full table search.

Adding new attributes

Sometimes, you may want to add a new field to an existing document that has already been saved in the database. If this is the case, the update() command comes to the rescue once again. You can add a new attribute and value by passing the corresponding JSON as an argument to the update() command.

For example, we may want to add a nationality field to every document in the people table. We can do so by running the following query:

r.table('people').update({"nationality": "English"})

Note that first, we select every document by not providing a filter, and then, we chain the update() command at the end of the query. Let's edit the data once again and change Alex's nationality to Spanish:

r.table('people').filter(r.row("name").eq("Alex")).update({"nationality": "Spanish"})

Finally, we can print the name and nationality attributes of all the documents in the table to make sure that the updates have succeeded:

Adding new attributes

As you can see from the preceding screenshot, the nationality field has been added correctly, and Alex's nationality has been set to Spanish.

Now that you've learned how to insert, update, and query data, let's look at how we can remove documents from a table.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.182.150