Filtering an embedded list in MongoEngine
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 com开发者_开发技巧prehensions?
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.
精彩评论