Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 491
pgrzesik Avatar asked Oct 17 '25 19:10

pgrzesik


1 Answers

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'}]})
like image 158
justcompile Avatar answered Oct 20 '25 21:10

justcompile