msiemens / tinydb

TinyDB is a lightweight document oriented database optimized for your happiness :)
https://tinydb.readthedocs.org
MIT License
6.84k stars 550 forks source link

Insert at index #458

Closed CSutter5 closed 2 years ago

CSutter5 commented 2 years ago

How do you insert data at index, example

db.insert({data: "example"}, 0)

I was looking through the docs and I could not find anything.

MrPigss commented 2 years ago

docs.

You have to pas a Document instead of a dict if you want to assign the id yourself. Also inserting with an id that already exists results in an assertionError doc_id {id} already exists.

Use upsert if you want to update if it exists and insert if not.

Does this solve your question?

msiemens commented 2 years ago

@PizzaRules668 There is not quite a concept of indexes in TinyDB, at least not in the sense of an array where the index is an offset for that array. TinyDB instead has document IDs which uniquely indentify the documents stored in TinyDB.

To insert a document with a custom ID, you can wrap it in tinydb.table.Document class, as @MrPigss already mentioned:

form tinydb.table import Document

db.insert(Document({'data': 'example'}, 1))
CSutter5 commented 2 years ago

Alright thanks for the help. Sorry for not responding earlier

msiemens commented 2 years ago

Sorry for not responding earlier

No worries, I wasn't particularly quick to respond either 🙂