Search multiple fields for multiple values in MongoDB?

To search multiple fields for multiple values in MongoDB, you can use the $text and $search operators. This requires creating a text index on the fields you want to search across.

Syntax

db.collection.createIndex({ 
    "field1": "text", 
    "field2": "text" 
});

db.collection.find({
    "$text": {
        "$search": "value1 value2"
    }
});

Sample Data

db.searchMultipleFieldsDemo.insertMany([
    {"_id": 100, "FirstSubject": "Java", "SecondSubject": "MongoDB"},
    {"_id": 101, "FirstSubject": "MongoDB", "SecondSubject": "MySQL"},
    {"_id": 102, "FirstSubject": "MySQL", "SecondSubject": "Java"}
]);
{
    "acknowledged": true,
    "insertedIds": [100, 101, 102]
}

Create Text Index

Before using $text search, create a text index on the fields ?

db.searchMultipleFieldsDemo.createIndex({
    "FirstSubject": "text",
    "SecondSubject": "text"
});

Example: Search Multiple Values

Search for documents containing "Java" OR "MongoDB" in any of the indexed fields ?

db.searchMultipleFieldsDemo.find({
    "$text": {
        "$search": "Java MongoDB"
    }
});
{ "_id": 102, "FirstSubject": "MySQL", "SecondSubject": "Java" }
{ "_id": 100, "FirstSubject": "Java", "SecondSubject": "MongoDB" }
{ "_id": 101, "FirstSubject": "MongoDB", "SecondSubject": "MySQL" }

Alternative: Using $or Operator

For exact field-specific matching without text indexing ?

db.searchMultipleFieldsDemo.find({
    "$or": [
        {"FirstSubject": {$in: ["Java", "MongoDB"]}},
        {"SecondSubject": {$in: ["Java", "MongoDB"]}}
    ]
});

Conclusion

Use $text search with text indexes for flexible, multi-field text searching. The $or operator with $in provides exact matching across specific fields without requiring indexes.

Updated on: 2026-03-15T00:28:09+05:30

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements