TinyDB in Python - Simple Database For Personal Projects

In this Python Tutorial, I want to show you how to work with TinyDB. TinyDB is a tiny, document oriented database which is perfect for small personal projects. The API is super simple and fun to use. I show you basic functionalities like adding, deleting, updating, and searching.

TinyDB is open sourced an can be found on GitHub.

You can find and test the code on GitHub.

Pros / Cons



pip install tinydb

Basic usage

See how to insert, search, update, delete, and list items in your database. You can find and test the code on GitHub.

from tinydb import TinyDB, Query db = TinyDB('db.json') User = Query() # type: tinydb.queries.Query def insert_user(): db.insert({'name': 'John', 'age': 22}) db.insert({'name': 'Max', 'age': 25}) db.insert({'name': 'Sarah', 'age': 21, 'city': 'New York'}) def search_user(): results = db.search(User.city == 'New York') # returns a list for res in results: print(res) # type: tinydb.database.Document # print(res.city) # Not allowed! print(res['city']) results = db.search(User.age > 21) for res in results: print(res) def update_user(): db.update({'age': 26}, User.name == 'Max') for item in db: print(item) # or results = db.search(User.name == 'Max') for res in results: res['age'] = 27 db.write_back(results) # write back results we retrieved # or get and update/remove by document_id def delete_user(): db.remove(User.name == 'John') # db.purge() # remove all def update_by_document_id(): #db.remove(doc_ids=[2]) # this will not create doc_id=2, but the next highest number #db.insert({'name': 'Jason', 'age': 40}) item = db.get(doc_id=3) print(item) print(item.doc_id) db.update({'city': 'Boston'}, doc_ids=[1, 2]) #db.remove(doc_ids=[1, 2]) #### TESTS #### #db.purge() # empty db #insert_user() #search_user() #update_user() #delete_user() #update_by_document_id() print(db.all()) # for item in db: # print(item) #print(len(db)) # number of items

FREE VS Code / PyCharm Extensions I Use

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses