TinyDB – Logical OR
The “Logical OR” operator combines multiple conditions and evaluates to True only if either of the condition is met. TinyDB Logical OR operates on two queries of a database. If any one of the queries is True, TinyDB will fetch the required data. On the other hand, if both the queries are False, it will return a blank.
Syntax
The syntax of TinyDB Logical OR is as follows −
db.search((Query().(query1) | (Query().(query2)
Here, field represents the part of data that we want to access. Query() is the object created of our JSON table named student. It will fetch the data if any one of the conditions is met, otherwise it will return a blank.
Let”s take a couple of examples and see how it works. We will use the same student database that we have used in all the previous chapters.
Example 1
Let”s see what our TinyDB Student database returns when we apply Logical OR on the “st_name” and “subject” fields and check the following conditions: “st_name=lakhan” and “subject=TinyDB” −
from tinydb import TinyDB, Query db = TinyDB(''student.json'') db.search ((Query().st_name == ''lakan'') | (Query().subject == ''TinyDB''))
This query will fetch the following rows −
[ { "roll_number":1, "st_name":"elen", "mark":250, "subject":"TinyDB", "address":"delhi" }, { "roll_number":4, "st_name":"lakhan", "mark":200, "subject":"MySQL", "address":"mumbai" }, { "roll_number":5, "st_name":"karan", "mark":275, "subject":"TinyDB", "address":"benglore" } ]
Example 2
In this example, let”s apply Logical OR on the “subject” and “roll_number” fields −
from tinydb import TinyDB, Query db = TinyDB(''student.json'') db.search((student.subject.search(''M'')) | (student.roll_number < 5))
This query will fetch all the rows where the “subject” field starts with the letter “M” or the “roll_number” is less than “5”.
[ { "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":"lakhan", "mark":200, "subject":"MySQL", "address":"mumbai" } ]