Tinydb 简明教程
TinyDB - Upserting Data
我们讨论了 update 和 insert 查询,但有时,我们需要更新和插入的混合。在这种情况下,TinyDB 提供了一个独特的 upsert 查询。此查询有助于我们根据条件一次插入和更新数据。它有两种工作方式 −
We discussed the update and insert queries, but sometimes, we a need a mix of both update and insert. In such cases, TinyDB provides a unique upsert query. This query helps us to insert and update data at a time as per the condition. It works in two ways −
-
If data is available, then it chooses the update operation.
-
If data is not available, then it chooses the insert operation.
Syntax
upsert 查询的语法如下 −
The syntax of upsert query is as follows −
db.upsert({ 'key' : 'value', 'logged - in' : True}, regular expression)
让我们举几个示例来说明如何在 TinyDB 中使用此 upsert 查询。我们将使用与我们在前面所有章节中使用的相同的 student 数据库。
Let’s take a couple of examples to demonstrate how you can use this upsert query in TinyDB. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看如何使用 upsert 查询将学号为 2 的学生的地址更改为“surat”。在这种情况下,我们有一个匹配的用户,因此它将使用地址更新为已登录并设置为 True −
Let’s see how we can use the upsert query to change the address of a student to "surat", whose roll numbe is 2. In this case, we we have a matching user, hence it will update with the address to have logged-in set to True −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.upsert({'address':'Surat'}, Query().roll_number==2)
它将生成以下 output ,这意味着记录号“2”已更新。
It will produce the following output, which means record number "2" got updated.
[2]
使用以下代码验证记录号“2”是否已更新 −
Use the following code to verify whether record number "2" got updated or not −
db.get(doc_id=2)
它将显示更新后的数据-
It will show the updated data −
{
'roll_number': 2,
'st_name': 'Ram',
'mark': [250, 280],
'subject': ['TinyDB', 'MySQL'],
'address': 'Surat'
}
Example 2
让我们看看如何将 upsert 查询用于我们表中不可用的数据 −
Let’s see how we can use the upsert query for unavailable data in our table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.upsert({'E-mail':'ram@gmail.com','logged-in': True},
Query().roll_number==2)
它将显示以下输出,这意味着 ID 为“2”的文档已更新。
It will show the following output, which means the document with the ID "2" got updated.
[2]
使用以下代码验证更新的值 −
Use the following code to verify the updated values −
db.get(doc_id=2)
它将生成如下输出:
It will produce the following output −
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"Surat",
"logged-in":true,
"E-mail":"ram@gmail.com"
}
请注意,我们使用 upsert 查询创建了一个新键( E-mail )(该键不存在),并为其提供了值“ * ram@gmail.com* ”。
Notice that we used the upsert query to create a new key (E-mail) which was non-existent and supplied it with the value "ram@gmail.com".