如何替换/更新 MongoDB 数据库中集合的 mongoengine ListField 元素? 在蟒蛇中

问题描述

我刚刚学习 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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...