MongoDB full text search inside embedded object MongoDB full text search inside embedded object json json

MongoDB full text search inside embedded object


This: db.post.createIndex({"data.title":"text"}) is the correct command to create a text index on an embedded field.

This: db.post.find( { $text: { $search: "Hello" } } ) is the correct way of engaging the text index to search for the value Hello in the embedded field: data.title.

You are doing everything correctly. To verify this, I have taken your document, written it to a collection, created a text index on that collection using the createIndex() command you supplied and searched for it using the find() command you supplied and that document is returned.

So, perhaps the issue is elsewhere. I would suggest that you:

  • Confirm that the text index was definitely created. You can do this by running db.post.getIndexes(), if the text index is present and does cover data.title then you should see something like this in the output from that command:

    {    "v" : 2,    "key" : {        "_fts" : "text",        "_ftsx" : 1    },    "name" : "data.title_text",    "ns" : "<your database name>.post",    "weights" : {        "data.title" : 1    },    "default_language" : "english",    "language_override" : "language",    "textIndexVersion" : 3}
  • Confirm that there is definitely a document with data.title containing Hello. You can do this by running a simple find: db.post.find({'data.title': { $regex: /Hello/ } }).

  • Confirm that this command: db.post.find( { $text: { $search: "Hello" } } ) definitely uses your text index. You can do this by invoking that command with .explain() (e.g. db.post.find( { $text: { $search: "Hello" } } ).explain()) and the output should include something like this:

        "inputStage" : {        "stage" : "TEXT_MATCH",        "inputStage" : {            "stage" : "TEXT_OR",            "inputStage" : {                "stage" : "IXSCAN",                "keyPattern" : {                    "_fts" : "text",                    "_ftsx" : 1                },                "indexName" : "data.title_text",                "isMultiKey" : true,                "isUnique" : false,                "isSparse" : false,                "isPartial" : false,                "indexVersion" : 2,                "direction" : "backward",                "indexBounds" : {}            }        }