Mongodb: How to index multiple nested text fields?

I have the following json in my database:

{ 
    "_id" : "519817e508a16b447c00020e", "keyword" : "Just an example query", 
    "results" : 
    {
        "1" : {"base_domain" : "example1.com", "href" : "http://www.example1.com/"},
        "2" : { "base_domain" : "example2.com", "href" : "http://www.example2.com/"},
        "3" : { "base_domain" : "example3.com", "href" : "http://www.example3.com/"},
        "4" : { "base_domain" : "example4.com", "href" : "http://www.example4.com/"},
        "5" : { "base_domain" : "example5.com", "href" : "http://www.example5.com/"},
        "6" : { "base_domain" : "example6.com", "href" : "http://www.example6.com/"},
        "7" : { "base_domain" : "example7.com", "href" : "http://www.example7.com/"},
        "8" : { "base_domain" : "example8.com", "href" : "http://www.example8.com/"},
        "9" : { "base_domain" : "example9.com", "href" : "http://www.example9.com/"},
        "10" : { "base_domain" : "example10.com", "href" : "http://www.example10.com/"}
    } 
}

      

My goal is to get results for the following query:

> db.ranking.find({ $text: { $search: "http://www.example9.com"}})

      

It works when I create an index on all textboxes

> db.ranking.ensureIndex({ "$**": "text" }))

      

But not when I create an index only on the "results" field:

> db.ranking.ensureIndex( {"results" : "text"} )

      

Why?

+3


source to share


1 answer


The problem is that "results" are not a field, but a sub-document. The syntax for creating an index on text fields for MongoDB requires either a notation for all fields, "$ *" that you are using correctly, or a list of all text fields:

Create text index

You can create a text index on a field or fields whose value is a string or an array of string elements. When creating a text index on multiple fields, you can specify individual fields or use ($ **).

http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/



In your case, it will look like this:

db.ranking.ensureIndex(
                           {
                             "keyword": "text",
                             "results.1.href": "text",
                             "results.1.href": "text",
                             "results.2.href": "text",
                             "results.3.href": "text",
                             "results.4.href": "text",
                             "results.5.href": "text",
                             "results.6.href": "text",
                             "results.7.href": "text",
                             "results.8.href": "text",
                             "results.9.href": "text",
                             "results.10.href": "text"
                           }
                       )

      

+3


source







All Articles