简体   繁体   English

Pymongo,MongoDB 更新文档

[英]Pymongo, MongoDB update documet

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.好吧,我正在尝试使用 pymongo 上的 update_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:基本即时尝试在 qrtly_results 中创建新项目,但每次我使用 update_one 尝试添加新结果,update_one 替换数据,这是我尝试使用的命令:

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:我正在尝试在键“qrtly_results”中创建几个新文档,如下所示:

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

You might want to consider making qrtly_result an array, as your type of update is much easier for arrays;您可能需要考虑将qrtly_result数组,因为您的更新类型对于 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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM