【问题标题】:PyMongo iterate through documents / arrays within documents, replace found valuesPyMongo 遍历文档中的文档/数组,替换找到的值
【发布时间】:2018-09-09 00:32:35
【问题描述】:

我在MongoDB中有以下数据:

{ "_id" : 1, "items" : [ "apple", "orange", "plum" ] }
{ "_id" : 2, "items" : [ "orange", "apple", "pineapple" ] }
{ "_id" : 3, "items" : [ "cherry", "carrot", "apple" ] }
{ "_id" : 4, "items" : [ "sprouts", "pear", "lettuce" ] }

我正在尝试使用 Python / PyMongo 创建一个函数,该函数需要 2 个参数,一个旧字符串和一个新字符串。我想在所有文档的所有数组中找到所有“apple”,并将它们替换为字符串“banana”。

下面是我目前的代码:

def update(old, new):
    for result in db.collection.find({"items" : old}):
        for i in result["items"]:
            if i == old:
                db.collection.update({"_id": result["._id"]}, {"$set": {"items": new}})

【问题讨论】:

  • def update(old, new): for result in db.collection.find({"items" : old}): db.collection.update({ doc['_id'], items: old}, { $set: {"items.$" : new }}) #这也不起作用

标签: python arrays pymongo


【解决方案1】:

使用update_many() 在一个查询中更新多个文档,而不是遍历文档。
从 pymongo 导入 MongoClient

mongo_client = MongoClient(127.0.0.1, 27017)
db = mongo_client.my_databse

def update(old, new)
     db.collection.update_many({'items': old}, { '$set' : {'items.$' : new}})

对于小于 3.2 的 pymongo,使用带有多标志的更新

def update(old, new)
     db.collection.update({'items': old}, { '$set' : {'items.$' : new}}, multi=True)

【讨论】:

    【解决方案2】:

    终于想通了,其实很简单:

    from pymongo import MongoClient
    
    mongo_client = MongoClient(127.0.0.1, 27017)
    db = mongo_client.my_databse
    
    def update(old, new)
        for result in db.collection.find({'items' : old}):
            db.collection.update_one({ '_id': result['_id'], 'items': old}, { '$set' : {'items.$' : new}})
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 2017-04-15
      • 2012-06-02
      • 2015-10-05
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多