4

将文档插入 TinyDB 数据库时是否可以定义文档 ID?例如(来自教程)https://pypi.python.org/pypi/tinydb

from tinydb import TinyDB, where

from tinydb import TinyDB, where
db = TinyDB('./db.json')
db.insert({'int': 1, 'char': 'a'})
db.insert({'int': 1, 'char': 'b'}

但是如果我们看到生成的文档:

{"_default": {"1": {"int": 1, "char": "a"}, "2": {"int": 1, "char": "b"}}}

诸如“1”和“2”之类的 id 由 TinyDB 自动决定。插入文档时是否有选择该 ID 的方法?另外,可以做一个upsert吗?

谢谢!:)

4

1 回答 1

2

Yes, you could choose the internal id doc_id.

 from tinydb import table, TinyDB, Query
 
 db = TinyDB('db.json')
 db.insert(table.Document({'name': 'John', 'age': 22}, doc_id=12))

This is the output:

 {"_default": {"12": {"name": "John", "age": 22}}}

And yes, this works also with upsert.

User = Query()
db.upsert(table.Document({'name': 'John', 'age': 50}, doc_id=12), User.name == 'John')
于 2020-12-03T22:38:15.667 回答