过滤MongoEngine中的嵌入列表(Filtering an embedded list in MongoEngine)

编程入门 行业动态 更新时间:2024-10-21 09:20:28
过滤MongoEngine中的嵌入列表(Filtering an embedded list in MongoEngine)

如果我有这些型号:

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.

更多推荐

本文发布于:2023-07-07 21:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   MongoEngine   Filtering   list   embedded

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!