MongoDB – how to search for a value across two fields?

I have a simple collection that looks like this:

{'sold': 'Test1', 'bought': 'Test2'}, {'sold': 'Test3', 'bought': 'Test3'}, {'sold': 'Test3', 'bought': 'Test1'}

I need to get all the records where Test1 is either in sold or bought, so in thi case i should get the first and third records.

I tried this: db['orders'].find({'$or': [{'sold': 'Test1', 'bought': 'Test1'}]}), but the problem with this query is that it tries to get all the records where both sold and bought are equal to Test1. How can i get, instead, the records where sold or bought is equal to Test1?


you are able to do this by

db['orders'].find({'$or': [{'sold': 'Test1'}, {'bought': 'Test1'}]})

The $or operator expects a list of expressions, which are in your case {'sold': 'Test1'} and {'bought': 'Test1'}

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

for more details check out mongodb docs for OR.

Happy trading 🙂