4

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! :)

dsncode
  • 2,407
  • 2
  • 22
  • 36
  • Why do you want to do that? The keys are for tinydb's internal use. If you want to filter there are special functions for that. – MrLeeh Dec 15 '16 at 15:51
  • I would like to keep only 1 copy of a document and update it later if necesary. so, if I can't manage its ids... then I can't guarantee those documents are unique. – dsncode Dec 16 '16 at 06:08
  • Why don't you just add an extra id to your dictionary that you can use to identify your documents? – MrLeeh Dec 16 '16 at 07:31
  • 1
    This just became useful for me actually; since I'm using it for a discord bot, using user IDs as keys in some tables seems more reasonable than trying to query all documents to find the matching ID. There probably are similar cases where this is useful – dzshn Sep 19 '21 at 23:04

1 Answers1

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')
ikreb
  • 2,133
  • 1
  • 16
  • 35