Tinydb 简明教程
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
借助此查询,我们可以获取数据库中的文档数。它的 syntax 如下 −
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
get 查询用于检索与查询匹配的特定文档。它的 syntax 如下 −
The get query is used to reterive specific documents matching a query. Its syntax is as follows −
db.get(query)
The contains Query
contains 查询用于检查数据库是否包含匹配的值。其 syntax 如下 −
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
count 查询用于检索数据库中匹配文档的数量。其 syntax 如下 −
The count query is used to retrieve the number of matching documents from a database. Its syntax is as follows −
db.count(query)
我们举几个例子来理解如何在 TinyDB 中使用这些查询。我们将使用与前几章中相同的 student 数据库。
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
我们来看看如何使用 len() 查询来获取数据库中的文档数 −
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
我们看看如何使用 get() 查询从数据库中获取特定文档 −
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')
此查询将获取 "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
我们看看如何使用 contains() 查询来验证我们的数据库是否包含特定值 −
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')
contains() 查询基于给定数据库中是否存在指定值,返回一个布尔值。在本例中,它将返回 "True",因为我们的数据库具有 "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
我们来看看如何使用 count() 查询来获取给定条件为 True 的文档数 −
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'))
它将返回以下 output −
It will return the following output −
3
这意味着数据库中有 3 个文档的 "subject" 键的值为 "NoSQL"。
It means there are 3 documents in the database where the "subject" key has the value "NoSQL".