Laurent
Laurent

Reputation: 589

How to perform a $and search with Python and MongoDB

Let's say I have a list of keywords and I want to match against MongoDB documents in which they all appear in the keys field (that is, a AND clause).

How can I do that in Python?

I've tried:

keywords = ['a', 'b', 'c']
keywords_dict = {'keys' : keywords}
results = collection.find(keywords_dict)

But it seems to return no result.

I'm using Python3.5 with PyMongo.

Any hints?

Upvotes: 1

Views: 38

Answers (1)

chridam
chridam

Reputation: 103345

You can use the $all operator which is also equivalent to an $and operation of the specified values; i.e. the following statement:

{ 'keys': { '$all': ['a', 'b', 'c'] } }

is equivalent to:

{ '$and': [ { 'key': a }, { 'key': b }, { 'key': c} ] }

Upvotes: 1

Related Questions