MongoDB: update dictionary in document
from mongoDb website look at "Set Fields in Embedded Documents"
To specify a <field> in an embedded document or in an array, use dot notation.For the document matching the criteria _id equal to 100, the followingoperation updates the make field in the details document:db.products.update({ _id: 100 },{ $set: { "details.make": "zzz" } })
in your case
db.collection.update( {_id:ObjectId("1")}, { $set: { "occurrences.12": "3", "occurrences.17": "2" }})
I wrote a function to convert a dictionary to a new dictionary which only updates fields in that dictionary:
def convert_2_dict_mongodb(obj): result = {} for key, val in obj.items(): if not isinstance(val, dict): result[key] = val continue for sub_key, sub_val in val.items(): new_key = '{}.{}'.format(key, sub_key) result[new_key] = sub_val if not isinstance(sub_val, dict): continue result.update(convert_2_dict_mongodb(result)) if new_key in result: del result[new_key] return result
Example:
abc = { 'a': 1, 'b': { 'x': 1, 'y': 2, 'z': { 'g': 1, 'h': { 'e': [1, 2, 3] } } }, 'h': { 'a': [1, 2, 3] }}
To:
{'h.a': [1, 2, 3], 'b.x': 1, 'b.z.h.e': [1, 2, 3], 'b.z.g': 1, 'a': 1, 'b.y': 2}