Querying a list in mongoengine; contains vs in

前端 未结 1 563
野的像风
野的像风 2021-01-06 09:04

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.obj         


        
相关标签:
1条回答
  • 2021-01-06 09:09

    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')}
    

    Which is a direct lookup.

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

    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.

    0 讨论(0)
提交回复
热议问题