Mongoengine Listfield is a sub of a list

639 Views Asked by At

I have a document

class A(Document):
    name = StringField()
    my_list = ListField(StringField())

and my class data is:

A1.my_list = [1, 2, 3, 4]
A2.my_list = [5, 6, 7, 8]

My condition list is:

condition = [1, 2, 3, 4, 5]

How to I find that A1 has field "my_list" is sub list of my "condition"

P/S: The question is how I can build a Mongoengine Query to do that, I can't find all my records and compare by Python syntax

Yeah, I found the answer is $in in MongoDB and MongoEngine is __in You could use:

A.objects(my_list__in=condition)

How ever, if your data list is:

A1.my_list = [1, 2, 3]
A2.my_list = [1, 6, 7, 8]

and condtion list is:

condition_list = [1, 9, 10, 11]

You could find both is fit. That mean mongoengine will match if there is an element be in both data list and condition list.

Better solution is $setIsSubset in MongoDB 3 http://docs.mongodb.org/manual/reference/operator/aggregation/setIsSubset/

I don't think MongoEngine have that feature so if you have this problem, use raw query in MongoEngine to resolve it.

Another Solution:

db.a.find({my_list: {"$not": {"$elemMatch": {"$nin" : condition }}}})

However that double negative make me sick. Any suggestion ?

0

There are 0 best solutions below