【问题标题】:How to update cursor docs in MongoDB with pymongo?如何使用 pymongo 更新 MongoDB 中的游标文档?
【发布时间】:2017-05-01 00:36:48
【问题描述】:

如何使用 pymongo 更新 MongoDB 中创建的文档?

例如:我有一个数据集:

name    weight    amount
-------------------------
apple     2         3
banana    2         5

我想得到水果的重量:重量 * 数量

name    weight    amount    total
-----------------------------------
apple     2         3        6
banana    2         5        10

如何更新游标文档????

myFile = [
    {"name":"Appel", "weight":2, "amount":3}, {"name":"banana", "weight":2, "amount":5}   
]

myCollection.insert_many(myFile)

fruits = myCollection.find()

for fruit in fruits:
    total = fruit["weight"]*fruit["amount"]
    ????? What should I do now? ?????

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    您可以使用新字段total 更新集合,如下使用replace_one()

    for fruit in fruits:
      fruit["total"] = fruit["weight"] * fruit["amount"]
      myCollection.replace_one({"_id": fruit["_id"]}, fruit)
    

    值得注意的是,您还应该考虑使用PyMongo Bulk Write Operations,尤其是Unordered Bulk Write Operations,而不是循环遍历集合并逐个保存文档

    根据您的用例,或者您也可以使用Aggregation Pipeline 来计算价值服务器端:

    db.fruits.aggregate([
      {$project:{name:1, 
               weight:1, 
               amount:1, 
               total:{$multiply:["$weight", "$amount"]}}},
      {$out:"fruits_modified"}
    ]);
    

    上面的聚合管道,投影一个新字段total,其乘法结果为weightamount字段。将结果保存到另一个名为 fruits_modified 的集合中。 然后,您可以删除 fruits 集合,并重命名 fruits_modified 以进行交换,例如:

    db.fruits.drop();
    db.fruits_modified.renameCollection("fruits");
    

    请注意,在删除集合时执行的任何操作可能会丢失。考虑这两种方法,并根据您的用例使用。

    【讨论】:

    • 嗨@Wan Bachtiar,感谢您的回答。但是我仍然对“save()”有疑问,我收到了警告:“DeprecationWarning: save is deprecated. Use insert_one or replace_one”。所以,如果我使用 insert_one() 或 replace_one(),那么,我必须给一个过滤器作为第一个参数。是真的吗?
    • 我已更新代码以回答您的问题。现在它将搜索具有匹配 ObjectId 值的文档并将其替换为计算出的文档。
    猜你喜欢
    • 2021-11-30
    • 2015-08-27
    • 1970-01-01
    • 2021-06-22
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多