在MongoEngine中过滤嵌入式列表 [英] Filtering an embedded list in MongoEngine

查看:176
本文介绍了在MongoEngine中过滤嵌入式列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下型号:

class Sub(EmbeddedDocument):
    name = StringField()

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

我想查询一个返回Mains的查询,并按现有名称过滤潜艇

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)

这将返回正确的市电,但是Subs始终是整个列表,而不是子集.如何只获得子集?我需要依靠列表理解吗?

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也不支持.

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

您可以对数组(列表)执行切片操作,但不能进行临时过滤. MongoDB数组中的切片与Python中的切片列表类似,您可以使用slice__关键字语法使用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])

这将返回从索引0(即第一个元素)开始的子元素,此后返回两个元素.

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

这篇关于在MongoEngine中过滤嵌入式列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆