MongoDB Search for all values in array

Viewed 849

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'})
2 Answers

Refer to $in operator. Example

db.collection.find( { field: { $in: [ 'hi' , 'value'] } } )

If you wanted to get documents which has all elements from input array then you need to use $all operator.

db.collection.find( { Field: { $all: [ 'hi' , 'bye'] } } ) // input array :: [ 'hi' , 'bye']

Above matches documents where field named Field has both values from passed in input array.

Test : mongoplayground

But if you wanted to get documents even if at least one element from input array matches, then you need to use $in operator.

db.collection.find( { Field: { $in: [ 'hi' , 'bye'] } } )

Test : mongoplayground

Related