Home > Software design >  How to query mongodb with Pymongo to get results based on multiple conditions on the same field
How to query mongodb with Pymongo to get results based on multiple conditions on the same field

Time:04-22

I have a mongo collection that contains data like:

{'email': '[email protected]'}
{'email': '[email protected]'}
{'email': '[email protected]'}

I want to get the the result of email that is [email protected] and [email protected], eg:

[{'email':'test1gmail.com'},{'email':'test2gmail.com'}]

is there a way I can do this with Pymongo's find?

I've tried using:

test.find({'email': '[email protected]', 'email':'[email protected]'})

But I think that's only getting the email [email protected] and not '[email protected]. If I do:

test.find({'email': '[email protected]', 'email':'[email protected]'})

That only gives me the results for [email protected].

Thought I would give $or a try based on Mongo DB query on multiple conditions:

test.find({"$or":[{'seller_email': '[email protected]', 'seller_email':'[email protected]'}]})

But that doesn't seem to work either.

I looked through the docs: https://pymongo.readthedocs.io/en/stable/tutorial.html, but I didn't see it.

I know you can do it from mongo's cli: MongoDB query with multiple conditions, but I need it to do it via pymongo.

CodePudding user response:

I think I found the issue, using the $or keyword should have worked. I've missed/misplaced some {}.

Should be:

test.find({"$or":[{'seller_email': '[email protected]'}, {'seller_email':'[email protected]'}]})

instead of:

test.find({"$or":[{'seller_email': '[email protected]', 'seller_email':'[email protected]'}]})

CodePudding user response:

I think you better referring to the official mongodb help pages, see here for querying methods: https://www.mongodb.com/docs/manual/tutorial/query-documents/ and refer to the ‘Or’ conditions which I believe would solve your problem.

  • Related