it is possible to input a document id on tinydb? an upsert is possible?

时间:2016-12-02 05:26:44

标签: python tinydb

it is possible to define a document id when inserting a document into a TinyDB database? for example (from the tutorial) 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'}

but if we see the generated document:

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

ids such as "1" and "2" where automatically decided by TinyDB. is there anyway to chose that id when inserting a document? also, it is possible to do an upsert?

thanks! :)

1 个答案:

答案 0 :(得分:1)

是的,您可以选择内部ID doc_id

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

这是输出:

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

是的,这也适用于upsert

User = Query()
db.upsert(table.Document({'name': 'John', 'age': 50}, doc_id=12), User.name == 'John')