如果我有这些型号:
class Sub(EmbeddedDocument): name = StringField() class Main(Document): subs = ListField(EmbeddedDocumentField(Sub))我想要一个返回Mains的查询,其中subs按名称进行过滤
Main.objects.filter(subs__name__exists=True)这将返回正确的Mains,但Subs始终是整个列表,而不是子集。 我怎样才能获得子集? 我需要依赖列表推导吗?
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?
最满意答案
MongoDB不支持您正在请求的此操作,因此Mongoengine也不支持。
您可以对阵列(列表)执行切片操作,但不能对ad-hoc过滤执行切片操作。 在MongoDB数组中切片的工作方式类似于在Python中切片列表,您可以使用slice__关键字语法使用Mongoengine进行slice__ :
Main.objects.filter(subs__name__exists=True).fields(slice__subs=[0,2])这将返回从索引0开始的subs(即第一个元素),然后返回两个元素。
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.
更多推荐
发布评论