How to delete record or document from TinyDB

10.4k views Asked by At

How to delete record or document from TinyDB

Example of DB:

{"1" : {"id_key" : "xxx", "params" : {} } },
{"2" : {"id_key" : "yyy", "params" : {} } },

I want to delete "1" if id_key=='xxx'

On TinyDB tutorial code below is suggested. How to complete it to delete record/document ?

db.update(delete('key1'), where('key') == 'value')
2

There are 2 answers

0
klitz1967 On

To use the example code for your data, type:

db.update(delete('id_key'), where('id_key') == 'xxx')

Please note: TinyDB is a key-value database. using the code above will remove the key 'xxx'. If you type:

db.all()

you will see that the key 'xxx' is deleted. but realize that the row still exists in the database AND if 'params' had any values in it, the values in 'params' would still exist.

A better alternative might be to use TinyDB's remove command, for example:

db.remove(where('id_key') == 'xxx')
0
pypie On

The current version of TinyDB (4.7.1) works as follows for removing a record/document by key. Assume the name of the key is 'key' and the document you want removed is the one where 'key' = 'xxx'. First get all documents in a query, then remove:

from tinydb import TinyDB, Query
db = TinyDB("your_database.json")
YourSelection=Query()
db.remove(YourSelection.key == 'xxx')