Aleksey Bilogur
Aleksey Bilogur

Reputation: 3846

How do you query MongoDB by pairs of keys using pymongo

I have a list of pairs of things, of the form e.g. [['A', 'B'], ['C', 'D']]. I want to query MongoDB for records in a specific collection which have properties matching both of these things.

For example, here is what I would want to get back:

[{'_id': ObjectId('...'),
  'first_property': 'A',
  'second_property': 'B'
 },
 {'_id': ObjectId('...'),
  'first_property': 'C',
  'second_property': 'D'
 }]

How do I query simultaneous properties using pymongo?

Upvotes: 0

Views: 65

Answers (1)

Aleksey Bilogur
Aleksey Bilogur

Reputation: 3846

I got pretty good performance out of the following pattern:

client.find({'$or': [{'property_a': value_a, 'property_b': value_b} for value_a, value_b in some_list_of_two_element_tuples]}

This creates a very long $or statement out of our requested tuples.

Upvotes: 1

Related Questions