I would like to be able to dynamically build a Mongo query using Node with multiple OR's. The point of this query is to do an AND search in the database with multiple search terms.
For example, suppose someone wanted to search for records containing the words "dog" and "cereal." The query would only return records that have "dog" and "cereal" somewhere in the record (i.e. the search terms can appear in different columns).
I know that the query should end up looking like this:
query = {
$and: [
{$or: [
{col1: {$regex: "first", $options: "i"}},
{col2: {$regex: "first", $options: "i"}}
]},
{$or: [
{col1: {$regex: "second", $options: "i"}},
{col2: {$regex: "second", $options: "i"}}
]}
]
}
My node code, however, does not produce this. This is the closest I have gotten to figuring this out:
var regexQueryWrapper = {};
regexQueryWrapper["$and"] = [];
var wrapper = {};
wrapper["$or"] = [];
var query = {};
searchTerms.forEach(function(term) {
searchFields.forEach(function(field) {
query[field] = {$regex: term, $options: 'i'};
wrapper["$or"].push(query);
});
regexQueryWrapper["$and"].push(wrapper);
});
What is the best way to do this? Is there a different approach that I am missing?