Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find all documents in a collection Mongodb by two values of the same key?

Tried to find the answer on the net, but somehow did not work. I have a collection from which I get a dataframe. I need to filter, that is, get all documents in which the key value will match a certain list of values.

Example collection:

_id: '1'
key_1: 'a'
key_2 : 'b'

_id: '2'
key_1: 'a'
key_2 : 'c'

_id: '3'
key_1: 'd'
key_2 : 'e'

_id: '4'
key_1: 'c'
key_2 : 'f'

Based on this small example, I’m trying to display all documents where there will be values in key_1 = a and d. That is, get documents with _id 1, 2 and 3 at the output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I use pomongo as well as compass, tried the following attempts but it was not successful:

db.collection.find({'key_1': ['a', 'd']})
db.collection.find({'key_1': 'a', 'key_1': 'd'})

Tell me how can this be done?

>Solution :

Use $in operator:

db.collection.find( { key_1: { $in: [ 'a', 'd' ] } })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading