pythonmongodbmongoengine

Mongoengine query listfield contains string matches


I have a ListField in models which contians string values. How do I query a string matches which are contains given string? I know contains operator do the need. But it matches exactly the given string is present.

For Example:

[
    {_id: 1, "name": "name1", "tags": ["abc", "efg", "ijk"]},
    {_id: 2, "name": "name2", "tags": ["bcd", "fgh", "jkl"]}
]

Model:

class Users(Document):
    name = StringField()
    tags = ListField(StringField())

Then my query is like

users = Users.objects(tags__icontains='bc')

Which I expect it returns both records contains bc

Note: For icontains operator works as expected when it is StringField, but for ListField it turns simply matches User.objects(tags='bc'). Refer

In addition to this, there is an option in mongo query with text matching, MongoDB query supports Perl notation of the regular expression. Like tags=/bc/. How do we do this with mongoengine. Refer


Solution

  • Finally I have done this with Regular expression matches.

    I have changed my query from

    users = Users.objects(tags__icontains='bc')

    to

        import re
        users = Users.objects(tags=re.compile('.*bc.*', re.IGNORECASE))
    

    Refer