【问题标题】:Pymongo extract documents, modify the documents and update with replaceone methodPymongo 提取文档,修改文档并使用 replaceone 方法更新
【发布时间】:2020-04-08 03:12:24
【问题描述】:

如何在不使用update 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)

这是我之前要更​​新的代码。由于不推荐使用保存方法,因此我想替换它。但我不想使用 mongodb 查询,但想使用 python 处理。

在这种情况下我该如何使用 replaceone?

【问题讨论】:

  • 您正在尝试更新 mongo 集合中的一个现有文档,并再次插入具有相同 ObjectId 的相同文档,这就是错误 desc 的含义。为什么不直接使用 update() 更新
  • mongodb._getCollection("RESULT").save(i)
  • @Valijon 非常感谢你,我正在寻找你的答案!
  • save() 已弃用。请改用replace_one()
  • @BellyBuster ,你能再检查一下这个问题吗?我改变了我的问题

标签: python mongodb


【解决方案1】:

使用db.collection.replace_one():

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

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 2015-11-18
    • 2012-12-03
    • 2014-10-18
    • 2014-10-24
    • 1970-01-01
    • 2017-05-31
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多