List of MongoEngine queries for objects that have properties starting with the prefixes listed

I need to query the Mongo database for items with a specific property starting with any prefix in the list. Now I have a code like this:

query = mymodel(terms__term__in=query_terms) 

and this corresponds to objects that have an element in the "terms" list that has a "term" StringField that is explicitly found in the "query_terms" list. What I want to achieve are objects that have an item in the terms list that has the term StringField, starting with any prefix that appears in the query_terms list. Is it possible to do this in one query and without storing any possible prefix "term" in the predicate? EDIT: The solution below works fine, but now I have to find objects with conditions starting with each prefix in the list. I changed

 query = reduce(lambda q1, q2: q1.__or__(q2), map(lambda prefix: Q(terms__term__startswith=prefix))) 

to

 query = reduce(lambda q1, q2: q1.__and__(q2), map(lambda prefix: Q(terms__term__startswith=prefix))) 

but it does not work. As a result, I get the following error:

 InvalidQueryError: Duplicate query conditions: terms__term__startswith 

Any ideas?

+6
source share
2 answers

If you request a term for this value, you can filter out the values ​​starting with perfectionism as follows:

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

If you need to filter out several prefixes, you will need to create Q objects for this:

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

If you need to create a 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) 
+9
source

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: did not notice that this question concerns mongoengine. The above applies to pure pimongo, I don’t know if ME permits this.

+2
source

Source: https://habr.com/ru/post/914316/


All Articles