TinyDB – Delete Data
In case you need to delete a particular set of data permanently from a TinyDB database, you can do so by using the remove() method. Like for reteriving and updating the data, you first need to create an instance of the Query class for deleting the data. You can use the following command for this purpose −
from tinydb import Query Student = Query()
Here, Student is the name of our database.
The remove() Method
Here is the syntax for the remove() method −
db.remove( Query() field regex )
The remove() method accepts both an optional condition as well as an optional list of documents IDs.
The student Database
We will use the following student database, for the examples in this chapter.
[ { "roll_number":1, "st_name":"elen", "mark":250, "subject":"TinyDB", "address":"delhi" }, { "roll_number":2, "st_name":"Ram", "mark":[ 250, 280 ], "subject":[ "TinyDB", "MySQL" ], "address":"delhi" }, { "roll_number":3, "st_name":"kevin", "mark":[ 180, 200 ], "subject":[ "oracle", "sql" ], "address":"keral" }, { "roll_number":4, "st_name":"lakan", "mark":200, "subject":"MySQL", "address":"mumbai" }, { "roll_number":5, "st_name":"karan", "mark":275, "subject":"TinyDB", "address":"benglore" } ]
Example: Deleting a Single Row of Data
Let”s take an example to understand the remove() method.
from tinydb import TinyDB, Query student = Query() db.remove(student.roll_number == 5)
The above query will delete the data where the student”s roll number is 5. It will return the ID of the removed object −
[5]
Now, we can use the all() method to see the updated database.
db.all()
It will display the data from the updated database −
[ { "roll_number":1, "st_name":"Adam", "mark":250, "subject":"TinyDB", "address":"delhi" }, { "roll_number":2, "st_name":"Ram", "mark":[ 250, 280 ], "subject":[ "TinyDB", "MySQL" ], "address":"delhi" }, { "roll_number":3, "st_name":"kevin", "mark":[ 180, 200 ], "subject":[ "oracle", "sql" ], "address":"keral" }, { "roll_number":4, "st_name":"lakan", "mark":200, "subject":"MySQL", "address":"mumbai" } ]
Example: Deleting Multiple Rows of Data
If you want to remove more than one row at a time, you can use the remove() method as follows −
from tinydb import TinyDB, Query student = Query() db.remove(student.roll_number > 2)
It will return the IDs of the removed object:
[3,4]
Use the all() method to see the updated database.
db.all()
It will display the data from the updated database −
[ { "roll_number":1, "st_name":"Adam", "mark":250, "subject":"TinyDB", "address":"delhi" }, { "roll_number":2, "st_name":"Ram", "mark":[ 250, 280 ], "subject":[ "TinyDB", "MySQL" ], "address":"delhi" } ]
Example: Deleting the Entire Data
If you want to remove all the data from a database, you can use the truncate() method as follows −
db.truncate()
Next, use the all() method to see the updated database.
db.all()
It will show an empty database as the output −
[]