简体   繁体   中英

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.

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?

Use $in operator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM