Mongodb 2.6+ has built in support for text searches using the $text
operator. Here's how to use it.
Build an text index on the desired searchable fields. Note: For MongoDB 2.6 you can only have 1 text index on a collection.
Create text index on one field
db.test.ensureIndex({
"field1" : "text"
}, { name : "Field1TextIndex"});
Create text index on two fields
db.test.ensureIndex({
"field1" : "text",
"field2" : "text"
}, { name : "Field12TextIndex"});
Create text index for any string field
db.test.ensureIndex({
"$**" : "text"
}, { name : "AllTextIndex"});
Query the collection using the $text operator.
Here's the format for $text
{ $text: { $search: <string of keywords>, $language: <string> } }
Example code
Setup
use test;
var createPerson = function(f,l,d){
return { firstName : f, lastName: l, description : d};
};
db.test.remove({});
db.test.insert(createPerson("Ben", "Dover", "Real Estate Agent"));
db.test.insert(createPerson("James", "Bond", "secret agent, ben's friend"));
Creating an text index on all string fields in a document.
db.test.ensureIndex({ "$**" : "text" }, { name : "AllTextIndex"});
Query all fields for keywords
Searching for ben
db.test.find({
$text : {
$search : "ben"
}
});
Output
{ "_id" : "...", "firstName" : "James", "lastName" : "Bond", "description" : "secret agent, ben's friend" }
{ "_id" : "...", "firstName" : "Ben", "lastName" : "Dover", "description" : "Real Estate Agent" }
The search for "ben" returned both documents since one had Ben
as the firstName
, and the other had ben's
in the description
field.
Querying for real friend
produces the same result.
db.test.find({
$text : {
$search : "real friend"
}
});
More info here: