Database Reference
In-Depth Information
In addition to creating compound indexes with other text fields, you can create compound indexes with other
non-text fields. You can build these indexes just as you would add any other index, as in this example:
db.texttest.ensureIndex( { content : "text", username : 1 });
This command creates a text index on the
content
portion of the document and a normal index on the
username
portion. This can be especially useful when using the
filter
parameter, as the filter is effectively a query on all the
subdocuments used. These, too, will need to be read either from the index or by reading the document itself. Let's
look at our example from earlier:
db.texttest.runCommand( "text", { search : "fish", filter : { about : "food" } })
Given the filter on this query, we will need to index the
about
portion of the document; otherwise, every
theoretically matched document would need to be fully read and then validated against, which is a costly process.
However, if we index as follows we can avoid those reads by having an index like this, which includes the
about
element:
db.texttest.ensureIndex( { about : 1, content : "text" });
Now let's run the
find
command again:
> db.texttest.runCommand( "text", { search : "fish", filter : { about : "food" } })
{
"queryDebugString" : "fish||||||",
"language" : "english",
"results" : [
{
"score" : 0.75,
"obj" : {
"_id" : ObjectId("51d7ccb36bc6f959debe5514"),
"number" : 1,
"body" : "i like fish",
"about" : "food"
}
}
],
"stats" : {
"nscanned" : 1,
"nscannedObjects" : 0,
"n" : 1,
"nfound" : 1,
"timeMicros" : 95
},
"ok" : 1
}
You can see that there are no scanned objects, which should improve the overall efficiency of the query. With these
options you should be able to drive some real flexibility and power into your text searching.
You should now see the enormous power of MongoDB's latest searching feature, and you should have the
knowledge to drive some real power from text searching.