TinyDB - Retrieving Data



After creating a database, we need to frequently retrieve the data from that database. Following are the ways by which we can reterive the data from a database −

The len() Query

With the help of this query, we can get the number of documents in a database. Its syntax is as follows −

len(db)

The get Query

The get query is used to reterive specific documents matching a query. Its syntax is as follows −

db.get(query)

The contains Query

The contains query is used to check whether the database contains a matching value or not. Its syntax is as follows −

db.contains(query)

The count Query

The count query is used to retrieve the number of matching documents from a database. Its syntax is as follows −

db.count(query)

Let's take a few examples to understand how these queries work in TinyDB. We will use the same student database that we have used in all the previous chapters.

Example 1

Let's see how we can use the len() query to get the number of documents in our database −

from tinydb import TinyDB
db = TinyDB('student.json')
print ("Number of documents in student db: ", len(db))

It will show the number of documents present in the specified database −

Number of documents in student db: 5

Example 2

Let's see how we can use the get() query to get a specific document from our database −

from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.get(Query().address == 'delhi')

This query will fetch the row where the "address" field has the value "delhi".

{
   'roll_number': 1,
   'st_name': 'elen',
   'mark': 250,
   'subject': 'TinyDB',
   'address': 'delhi'
}

Example 3

Let's see how we can use the contains() query to verify if our database contains a specific value −

from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.contains(Query().address == 'delhi')

The contains() query returns a Boolean value, based on the existence of the specified value in the given database. In this case, it will return "True" because our database does have a "address" key with the value "delhi".

True

Example 4

Let's see how we can use the count() query to get the number of documents for which a given condition is True −

from tinydb import TinyDB, Query
db = TinyDB('student.json')
print (db.count(Query().subject == 'NoSQL'))

It will return the following output

3

It means there are 3 documents in the database where the "subject" key has the value "NoSQL".

Advertisements