Filtering an embedded list in MongoEngine

2019-04-11 05:06发布

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条回答
混吃等死
2楼-- · 2019-04-11 05:45

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.

查看更多
登录 后发表回答