Filtering an embedded list in MongoEngine

徘徊边缘 提交于 2019-12-06 05:54:26

问题


If I have these models:

class Sub(EmbeddedDocument):
    name = StringField()

class Main(Document):
    subs = ListField(EmbeddedDocumentField(Sub))

I want to have a query that returns the Mains, with the subs being filtered by name existing

Main.objects.filter(subs__name__exists=True)

This returns the correct Mains, but the Subs are always the entire list, not a subset. How can I get only the subset? Do I need to rely on list comprehensions?


回答1:


MongoDB doesn't support exactly this operation that you're requesting, and therefore neither does Mongoengine.

You can perform slicing operations on arrays (lists), but not ad-hoc filtering. Slicing in MongoDB arrays works similarly to slicing lists in Python, and you can do it with Mongoengine using the slice__ keyword syntax:

Main.objects.filter(subs__name__exists=True).fields(slice__subs=[0,2])

This will return the subs starting at index 0 (i.e. the first element) and returning two elements after that.



来源:https://stackoverflow.com/questions/7368695/filtering-an-embedded-list-in-mongoengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!