0

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?

Miro Krsjak
  • 355
  • 1
  • 16

2 Answers2

0

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)
S.Uzair
  • 18
  • 3
0

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.

Miro Krsjak
  • 355
  • 1
  • 16