TinyDB
TinyDB is a lightweight, document-oriented NoSQL database for Python, optimized for simplicity and happiness. It stores data in human-readable JSON files and is designed for small applications that don't require a full-featured database server. Currently in maintenance mode (v4.8.2), it focuses on bugfixes and community-contributed features, with new releases for minor updates and patches.
Warnings
- breaking Version 4.0 introduced significant API changes, including renaming table management methods (e.g., `purge_tables` to `drop_tables`, `Table.purge()` to `Table.truncate()`) and changes to how `TinyDB` is initialized. Python 2 support was also dropped.
- breaking Version 3.0 changed querying syntax. `where('...').contains('...')` became `where('...').search('...')`. `where('foo').has('bar')` was replaced by property access (`where('foo').bar` or `Query().foo.bar`) or dictionary access (`Query()['a.b.c']`). Explicit `exists()` is now required to check for key existence. External packages are needed for `SmartCacheTable` and serialization features.
- gotcha When using property access for queries (e.g., `Query().field_name`), adding new query operations in later TinyDB versions might break code if your field name matches a new operation name (e.g., `Query().map` could break if a `map` operation is introduced).
- gotcha TinyDB is not designed for concurrent access from multiple processes or threads without external tools. Direct concurrent writes can lead to data corruption.
- gotcha Writing individual records using `db.insert()` can be very slow due to file I/O overhead for each operation.
Install
-
pip install tinydb
Imports
- TinyDB
from tinydb import TinyDB
- Query
from tinydb import Query
Quickstart
from tinydb import TinyDB, Query
import os
db_file = 'my_db.json'
# Clean up previous db file for fresh run
if os.path.exists(db_file):
os.remove(db_file)
# Initialize database
db = TinyDB(db_file)
# Insert documents
db.insert({'name': 'Alice', 'age': 30, 'city': 'New York'})
db.insert({'name': 'Bob', 'age': 24, 'city': 'London'})
db.insert({'name': 'Charlie', 'age': 30, 'city': 'Paris'})
# Query documents
User = Query()
alice = db.search(User.name == 'Alice')
print(f"Alice: {alice}")
people_in_30s = db.search(User.age >= 30)
print(f"People aged 30 or more: {people_in_30s}")
# Update documents
db.update({'age': 31}, User.name == 'Alice')
alice_updated = db.search(User.name == 'Alice')
print(f"Alice after update: {alice_updated}")
# Delete documents
db.remove(User.name == 'Bob')
all_users = db.all()
print(f"All users after Bob's removal: {all_users}")
# Clean up after example
os.remove(db_file)