Search multiple fields for multiple values in MongoDB
Found another answer through poring over the documentation that seems to hit a sweet spot -- text indexes.
db.collection.ensureIndex({"field1":"text","field2":"text"})db.records.runCommand("text",{search:"foo bar"})
When I run my actual query with many more strings and fields (and about 100,000 records), the $or/$in
approach takes 620 milliseconds while the text index takes 131 milliseconds. The one drawback is that it returns a different type of document as a result; luckily the actual documents are a parameter of each result object.
Thanks to those who took the time to make suggestions.
I would collect all the relevant fields in one field (i.e. collected
) by adding their values like
"foo:field1", "bar:field2", "baz:field3", "stuff:otherfield", "bar:field1", "baz:field2"...
into that field.
If you search for bar
existing in any field you can use:
db.collection.find( { collected: { $regex: "^bar" } }, ... );
Your example in the question would look like:
db.collection.find( collected: { { $all: [ "foo:field1", "foo:field2", "bar:field1", "bar:field2" ] } }, ... );