Google News
logo
TinyDB - Interview Questions
Explain the difference between the update and update_multiple methods in TinyDB.
In TinyDB, both the update() and update_multiple() methods are used to update documents in the database. However, they differ in terms of the number of documents they update and the flexibility they provide.

update() method :

* The update() method is used to update a single document in the database that matches the specified query condition.
* It takes two arguments: the update operations to apply and the query condition to identify the document(s) to update.
* If multiple documents match the query condition, only the first matching document is updated.
# Update a single document in the 'users' table where the 'name' is 'Alice'
users_table.update({'age': 31}, User.name == 'Alice')?

update_multiple() method :

* The update_multiple() method is used to update multiple documents in the database that match the specified query condition.
* It takes two arguments: the update operations to apply and the query condition to identify the document(s) to update.
* Unlike the update() method, update_multiple() updates all documents that match the query condition, not just the first one.
# Update all documents in the 'users' table where the 'age' is less than 25
users_table.update_multiple({'status': 'inactive'}, User.age < 25)?

In summary, the update() method is used to update a single document, while the update_multiple() method is used to update multiple documents. The choice between the two methods depends on whether you want to update only the first matching document or all matching documents.
Advertisement