【发布时间】: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 }}) #这也不起作用