Google News
logo
TinyDB - Interview Questions
How do you update documents in a TinyDB database?
To update documents in a TinyDB database, you can use the update() method. This method allows you to apply changes to existing documents based on specified query conditions. Here's how you can update documents in a TinyDB database:

Define the update operations : First, you need to specify the update operations that you want to apply to the documents. These operations are represented as a dictionary, where keys are the fields to update, and values are the new values to set for those fields.

Specify the query condition : Next, you need to define a query condition that identifies the documents you want to update. You can use the Query object or a lambda function to specify the condition.

Call the update() method : Finally, call the update() method on the table object, passing the update operations and the query condition as arguments.

Here's an example demonstrating how to update documents in a TinyDB database:

from tinydb import TinyDB, Query

# Create a new TinyDB instance with JSON file storage
db = TinyDB('db.json')

# Get a reference to the 'users' table
users_table = db.table('users')

# Define a Query object to specify the query condition
User = Query()

# Define update operations (e.g., set the 'age' field to 31 for users with 'name' equal to 'Alice')
update_operations = {'age': 31}

# Specify the query condition (e.g., find users with 'name' equal to 'Alice')
query_condition = User.name == 'Alice'

# Update matching documents in the 'users' table
users_table.update(update_operations, query_condition)?

In this example :

* We define a Query object User to specify the query condition.
* We define the update operations as a dictionary, setting the 'age' field to 31.
* We specify the query condition to find users with the 'name' equal to 'Alice'.
* We call the update() method on the 'users' table, passing the update operations and the query condition as arguments.

After executing this code, all documents in the 'users' table where the 'name' field is equal to 'Alice' will be updated to set the 'age' field to 31.
Advertisement