在mongoengine中查询列表;包含与 [英] Querying a list in mongoengine; contains vs in

查看:1012
本文介绍了在mongoengine中查询列表;包含与的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在具有ID(ReferenceField)的模型中有一个ListField,并且如果该列表中有某个ID,则需要进行查询. AFAIK我对此有2个选择:

I have a ListField in a model with ids (ReferenceField), and I need to do a query if a certain id is in that list. AFAIK I have 2 options for this:

Model.objects.filter(refs__contains='59633cad9d4bc6543aab2f39')

或:

Model.objects.filter(refs__in=['59633cad9d4bc6543aab2f39'])

在该用例中,哪个是最有效的?

Which one is the most efficient for this use case?

模型如下:

class Model(mongoengine.Document):
    refs = mongoengine.ListField(mongoengine.ReferenceField(SomeOtherModel))

根据我在mongoengine文档中可以阅读的内容, http://docs. mongoengine.org/guide/querying.html#string-queries 包含的确是一个字符串查询,但是在这里它也能令人惊讶地工作.但是我猜测__in效率更高,因为它应该针对列表进行优化,否则我错了吗?

From what I can read in the mongoengine documentation, http://docs.mongoengine.org/guide/querying.html#string-queries, contains is really a string query, but it works surprisingly here as well. But I'm guessing that __in is more efficient since it should be optimized for lists, or am I wrong?

推荐答案

通常在幕后的字符串查询都是正则表达式查询,因此效率较低.但是,例外是针对参考字段进行测试!以下查询是:

The string queries normally under the covers are all regex query so would be less efficient. However, the exception is when testing against reference fields! The following queries are:

Model.objects.filter(refs__contains="5305c92956c02c3f391fcaba")._query
{'refs': ObjectId('5305c92956c02c3f391fcaba')}

这是直接查找.

Model.objects.filter(refs__in=["5305c92956c02c3f391fcaba"])._query
{'refs': {'$in': [ObjectId('5305c92956c02c3f391fcaba')]}}

这可能效率较低,但可能非常微不足道.影响最大的将是文档的数量以及refs字段是否具有索引.

This probably is less efficient, but would probably be extremely marginal. The biggest impact would be the number of docs and whether or not the refs field has an index.

这篇关于在mongoengine中查询列表;包含与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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