Google News
logo
TinyDB - Interview Questions
How do you perform basic CRUD operations in TinyDB?
In TinyDB, basic CRUD (Create, Read, Update, Delete) operations are performed using methods provided by the database and table objects. Here's how you can perform each of these operations in TinyDB:

Create (Insert) : To create new documents and insert them into a table, use the insert() method. Pass a dictionary representing the document to be inserted as an argument.
from tinydb import TinyDB

# 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 new document to insert into the table
new_user = {'name': 'Alice', 'age': 30}

# Insert the new document into the 'users' table
users_table.insert(new_user)?

Read (Retrieve) : To retrieve documents from a table, use the search() method to perform a query. You can pass a Query object or a lambda function representing the query condition.
from tinydb import Query

# Create a Query object to specify the query conditions
User = Query()

# Define a query condition (e.g., find users with age greater than 25)
query_condition = User.age > 25

# Apply the query to the 'users' table and retrieve matching documents
matching_users = users_table.search(query_condition)

# Print the matching documents
for user in matching_users:
    print(user)?
Update : To update existing documents in a table, use the update() method. Pass a dictionary representing the update operations to be applied to matching documents, along with a query condition to specify which documents to update.
# Define update operations (e.g., set the age to 31 for users named 'Alice')
update_operations = {'age': 31}

# Apply the update operations to matching documents
users_table.update(update_operations, User.name == 'Alice')?

Delete : To delete documents from a table, use the remove() method. Pass a query condition to specify which documents to remove.
# Define a query condition (e.g., delete users with age less than 18)
delete_condition = User.age < 18

# Remove matching documents from the table
users_table.remove(delete_condition)?

These are the basic CRUD operations that you can perform in TinyDB to create, read, update, and delete data in your database. By using these methods in combination with query conditions, you can manipulate data stored in TinyDB tables according to your application's requirements.
Advertisement