如何在mongoengine中删除文档的另一个嵌入文档中的嵌入文档项
How to remove an item of embedded document in another embedded document of a document in mongoengine
我的模特:
class City(EmbeddedDocument):
name = StringField()
population = IntField()
class Privince(EmbeddedDocument):
name = StringField()
cities = ListField(EmbeddedDocumentField(City))
class State(Document):
name = StringField()
provinces = ListField(EmbeddedDocumentField(Privince))
我可以使用以下代码删除一个州的 Province
:
State.objects(name="Alaska").update_one(pull__provinces={"name": "Juneau"})
但我不知道如何删除 province
的城市。
哦,我找到了一个非常简单的方法! :
state_obj = State.objects.get(name="Alaska")
province_obj = state_obj.provinces({"name": "Juneau"})
for city in province_obj.cities:
if city.name == "Test_City" and city.population == 10000:
province_obj.cities.remove(city)
我的模特:
class City(EmbeddedDocument):
name = StringField()
population = IntField()
class Privince(EmbeddedDocument):
name = StringField()
cities = ListField(EmbeddedDocumentField(City))
class State(Document):
name = StringField()
provinces = ListField(EmbeddedDocumentField(Privince))
我可以使用以下代码删除一个州的 Province
:
State.objects(name="Alaska").update_one(pull__provinces={"name": "Juneau"})
但我不知道如何删除 province
的城市。
哦,我找到了一个非常简单的方法! :
state_obj = State.objects.get(name="Alaska")
province_obj = state_obj.provinces({"name": "Juneau"})
for city in province_obj.cities:
if city.name == "Test_City" and city.population == 10000:
province_obj.cities.remove(city)