Pymongo, MongoDB update documet

Viewed 20

Well im trying to create news documents into my database, using the update_one on pymongo, but they are replacing the data and not create a new one.

Follow below my DB schema:

{
    'id': 123,
    'stock': 'Facebook',
    'code': 'fb',
    'qrtly_result': {
        '31/12/2020': {
            'item1': 123,
            'item2': 123,
            'item3': 123,
            'item4': 123,
        },
    }
}

Basic im trying to create new items inside the qrtly_results, but everysingle time i use update_one to try add new result, the update_one replace the data, this is the command im trying to use:

new_result = {
    '30/09/2020': {
        'item1': 123,
        'item2': 123,
        'item3': 123,
        'item4': 123,
    },
}


collection.update_one(
    {'stock': 'Facebok'},
    {'$set': {'qrtly_result': new_result}},
    upsert=True
)

I'm trying to create several new documents inside the key 'qrtly_results', like this:

{
    'id': 123,
    'stock': 'Facebook',
    'code': 'fb',
    'qrtly_result': {
        '31/12/2020': {...},
        '31/09/2020': {...},
        '31/03/2020': {...},
        '31/12/2019': {...},
        '31/09/2019': {...},
    }
}
1 Answers

You might want to consider making qrtly_result an array, as your type of update is much easier for arrays; if you want to stick to adding objects, your query is:

new_result = {
    'item1': 123,
    'item2': 123,
    'item3': 123,
    'item4': 123,
}

x = collection.update_one(
    {'stock': 'Facebook'},
    {'$set': {'qrtly_result.30/09/2020': new_result}},
    upsert=True
)
Related