问题描述
我刚刚学习 MongoDB 查询,几个小时以来我一直在尝试执行以下操作: 我有一个类定义为
class Uni(mongoengine.Document):
instruments =mongoengine.ListField(mongoengine.ReferenceField(Instrument))
其中 Instrument 是另一个 Document 对象。现在我想在 ListField 中找到对 Instrument 对象“old_instrument”的特定引用,并用对“new_instrument”的引用替换该引用。我一直在尝试以下方法:
Uni.objects(instruments=old_instrument).update(**{"set__$":new_instrument})
有人可以帮我详细说明一下解决方案吗?非常感谢!
解决方法
所以我找到的解决方案是先从数据库中读取数组,然后对其进行修改并将其更新回数据库。好像没有直接查询的解决办法。
for u in Uni.objects(instruments=old_instrument):
instr_array=u['instruments']
instr_array=[new_instrument if x == old_instrument else x for x in instr_array]
Uni.objects(name=u.name,date=u.date).update_one(upsert=True,instruments=instr_array)