pgrzesik
pgrzesik

Reputation: 2427

How to construct query to filter by pairs of keys in MongoDB?

let's assume that I have collection called my_collection, with three documents:

{'_id": 1, 'foo': 'foo_val', 'bar': 'bar_val'},
{'_id": 2, 'foo': 'foo_val2', 'bar': 'bar_val2'},
{'_id": 3, 'foo': 'foo_val', 'bar': 'bar_val2'}

I'd like to query it by given pairs of key-values, in this case e.g. I'd like to filter it by:

[{'foo': 'foo_val', 'bar': 'bar_val'}, {'foo': 'foo_val2', 'bar': 'bar_val2'}]

so it should return documents with ids 1 and 2.

It there an elegant way to do this in one call to db? I tried using the $in keyword, but it doesn't work as I want.

Upvotes: 4

Views: 281

Answers (1)

justcompile
justcompile

Reputation: 3542

You'll want to use the $or operator:

db.your_collection.find({$or:[{'foo': 'foo_val', 'bar': 'bar_val'},{'foo': 'foo_val2', 'bar': 'bar_val2'}]})

Upvotes: 6

Related Questions