Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Search for all values in array

Given an array of values I need to search through a MongoDB collection and return the combined results without making multiple find calls to the database. I would like to make a single call to the database and get the combined results

This is what I currently do (not exactly but its similar):

searchArray = ["hi", "bye"]
for item in searchedArray:
    db.collection.find({"Field": item})

The problem with this is that I cannot combine the results that each .find call returned. This approach is also making several .find calls to the database(one for every elements in the searchedArray). I would like to make a single call and get all the combined results back.

Is there any way to do something like this but with every element of a given array and get all the combined results back:

searchedArray = ["hi", "bye"]
results = db.collection.find({"Field": 'hi'} and {"Field": 'bye'})
like image 980
Alex Avatar asked Jun 09 '26 21:06

Alex


1 Answers

Refer to $in operator. Example

db.collection.find( { field: { $in: [ 'hi' , 'value'] } } )
like image 163
nayakam Avatar answered Jun 11 '26 12:06

nayakam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!