Miro Krsjak
Miro Krsjak

Reputation: 363

TinyDB update only part of document

I am unable to find a way how to update only part of a TinyDB document (one entry in an array). For example:

{ "name": "first", entries: [ { "id": 1, "count": 1 }, { "id": 2, "count": 33 } ] }

Is there a way only update the entry object with id 2?

Upvotes: 0

Views: 343

Answers (2)

Miro Krsjak
Miro Krsjak

Reputation: 363

Actually I moved away from using arrays when possible, and use more the key:value as a substitution. This is much better i think, it survives also possible concurent updates, and you can use custom transform formula to handle long keys.

Upvotes: 0

S.Uzair
S.Uzair

Reputation: 18

Yes, you can use the update method of TinyDB to update a specific entry in an array of a document. Here's an example:

from tinydb import TinyDB, Query

db = TinyDB('example.json')

# Get the document with the name "first"
doc = Query().name == 'first'
result = db.search(doc)

# Get the index of the entry with id=2 in the "entries" array
index = None
for i, entry in enumerate(result[0]['entries']):
    if entry['id'] == 2:
        index = i
        break

# Update the "count" value of the entry with id=2
if index is not None:
    result[0]['entries'][index]['count'] = 42
    db.update({'entries': result[0]['entries']}, doc)

Upvotes: 0

Related Questions