MongoEngine query list for objects having properties starting with prefixes specified in a list

醉酒当歌 提交于 2019-12-05 06:17:58

If your querying a term for it's value, you can filter the values that begin with a perfix like so:

MyModel.objects.filter(terms__term__startswith='foo')

If you need to filter for multiple prefixes you'll have to create Q objects for that:

MyModel.objects.filter(Q(terms__term__startswith='foo') | Q(terms__term__startswith='bar'))

If you need to create the query dynamically:

prefixes = ['foo', 'bar', 'baz']
query = reduce(lambda q1, q2: q1.__or__(q2), 
               map(lambda prefix: Q(terms__term__startswith=prefix), prefixes))
MyModel.objects.filter(query)

You can use a regular expression like ^(prefix1 | prefix2 etc):

prefixes = [....]
regex = '^(%s)' % '|'.join(map(re.escape, prefixes))
docs = your_collection.find({'term': {'$regex': regex}})

upd: didn't notice this question is about mongoengine. The above is for pure pymongo, don't know if ME allows this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!