BenjaminK
BenjaminK

Reputation: 783

MongoDB Python Update/ Insert dict in dict without overwriting

I can't insert my new document value (dict) without overwriting my existing data. I've looked through all different resources and can't find an answer. I've also though of putting the values from first_level_dict into a list "first_level_dict" : [dict1, dict2] but I won't know how to append the dict eighter.

Sample Data:

# Create the document

target_dict = {
    "_id": 55,
    "Root_dict": {
        "first_level_dict": {
            "second_level_dict1": {"Content1": "Value1"}
        }
    },
    "Root_key": "Root_value"
}
collection.insert_one(target_dict)

The result I'm looking for:

result_dict = {
    "_id": 55,
    "Root_dict": {
        "first_level_dict": {
            "second_level_dict1": {"Content1": "Value1"},
            "second_level_dict2": {"Content2": "Value2"}
        }
    },
    "Root_key": "Root_value"
}

Update: New Values example 2:

# New Values Sample

new_values = {
    "_id": 55,
    "Root_dict": {
        "first_level_dict": {
        "secon_level_dict2": {"Content2": "Value2"},
        "secon_level_dict3": {"Content3": "Value3"}
        }
    }
    collection.insert_one(target_dict)

Update: The result I'm looking for example 2:

result_dict = {
    "_id": 55,
    "Root_dict": {
        "first_level_dict": {
            "second_level_dict1": {"Content1": "Value1"},
            "second_level_dict2": {"Content2": "Value2"},
            "second_level_dict3": {"Content3": "Value3"},
        }
    },
    "Root_key": "Root_value"
}

What I've tried:

# Update document "$setOnInsert"
q = {"_id": 55}
target_dict = {"$set": {"Root_dict": {"first_level_dict": {"second_level_dict2": {"Content2": "Value2"}}}}}
collection.update_one(q, target_dict)

What I've tried example 2:

# Update document
q = {"_id": 55}
target_dict = {"$set": {"Root_dict.first_level_dict": {
    "second_level_dict2": {"Content2": "Value2"},
    "second_level_dict3": {"Content3": "Value3"}}}}
collection.update_one(q, target_dict)

Upvotes: 0

Views: 1211

Answers (1)

adamgy
adamgy

Reputation: 5643

Try using the dot notation:

target_dict = {$set: {"Root_dict.first_level_dict.second_level_dict2": {"Content2": "Value2"}}}

Additionally, to update/add multiple fields (for "example 2"):

target_dict = {$set: {
    "Root_dict.first_level_dict.second_level_dict2": {"Content2": "Value2"},
    "Root_dict.first_level_dict.second_level_dict3": {"Content3": "Value3"}
    }
}

Upvotes: 1

Related Questions