简体   繁体   English

Pymongo 提取文档,修改文档并使用 replaceone 方法更新

[英]Pymongo extract documents, modify the documents and update with replaceone method

How can I update the existing document by using python without using update mongodb query???如何在不使用更新 mongodb 查询的情况下使用 python 更新现有文档???

aa = mongodb.findByCollection(resultCollectionName, {})
totalCount = (aa.count())
count = 0
for document in aa:
    values = document["RESULTPERMONTH"].values()
    document["RESULT_SUM"] = sum(values)
    document["RESULT_AVG"] = roundTwoDigits(document["RESULT_SUM"] / len(document["RESULTPERMONTH"])) if len(document["RESULTPERMONTH"]) != 0 else -1000
    document["RESULT_LEN"] = len(document["RESULTPERMONTH"]) 
    document["RESULT_MIN"] = min(values) if len(values) != 0 else -1000
    if "buyInfo" in document:
        del document["buyInfo"]
    if "sellInfo" in document:
        del document["sellInfo"]
    try:
        mongodb.database.get_collection(resultCollectionName).save(document)
    except Exception as ex:
        print(ex)
    count = count +1
    if count % 10000 == 0:
        print(count / totalCount)

This is my previous code to update.这是我之前要更​​新的代码。 Since save method is deprecated, I would like to replace that.由于不推荐使用 save 方法,我想替换它。 But I don't want to use mongodb query but do want to use python processing.但我不想使用 mongodb 查询,但想使用 python 处理。

How can I use replaceone in this case?在这种情况下如何使用replaceone?

使用db.collection.replace_one()

db.collection.replace_one({'_id': aa['_id']}, document, upsert=True)

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

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