0

Since im fairly new to MongoDB (and databases in general), i wonder if this is the most pythonic way to modify one field in a nested entry. The field i want to change is stored in my collection "boards" like this:

_id: 270
checklist: {
    mechanical: {
        15: False
    }
}

All keys (checklist, mechanical and 15) are strings and refer to a bool value (False). The code on how i modify the data is the following:

# lock collection, define query
col = db["boards"]
query = {"_id": board_id}

# get data of one ID
document = col.find_one(query)
if document is None:
    print("Board id {0} invalid!".format(board_id))
    return

# modify document
document["checklist"][checklist][str(checklist_nr)] = set_to

# update whole document
col.update_one(query, {"$set": document})

As you can see, i always get the full document, modify it and write the full modified document again. Is there a way to just query this one field and modify it? I could not manage to do it, got errors like this, etc:

bson.errors.InvalidDocument: cannot encode object: {'15'}, of type: <class 'set'>
mnikley
  • 1,625
  • 1
  • 8
  • 21
  • Please post which code did you execute to get InvalidDocument error? – Antigluk Jan 29 '21 at 13:06
  • Thanks for your answer. Unfortunately i do not have the code anymore since i tried to keep my code clean. I tried to use queries with direct dict calls inside, e.g. using {}, [] in queries. I also tried accessing the dict inside the col.update_one command, e.g. col.update_one(query, {"$set: document["some_key"]["some key inside the other key"]: value_to_be_overwritten}). I cant reproduce the error properly anymore. – mnikley Feb 01 '21 at 14:01

0 Answers0