vcmkrtchyan
vcmkrtchyan

Reputation: 2626

How to do full text search on nested field in MongoDB?

I store my localization in MongoDB in the following way

db.user.insertMany([
    {
        "name": {
            "en": "Frodo Baggins",
            "ru": "Фродо Беггинс"
        }
    },
    {
        "name": {
            "en": "Bilbo Baggins",
            "ru": "Бильбо Беггинс"
        }
    }
])

I know that I can apply a full-text search index on all fields with this

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

but my document has lot of other information that I don't want to index. Is there any way to specify to index only the name field content?

Upvotes: 1

Views: 503

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17888

You can create a compound index on name.en and name.ru:

db.user.createIndex(
   {
     "name.en": "text",
     "name.ru": "text"
   }
 )

And use this query to search:

db.user.find( { $text: { $search: "Baggins" } }) 

You can even add a score value, and sort:

db.user
  .find({ $text: { $search: "Baggins" } }, { score: { $meta: "textScore" } })
  .sort({ score: { $meta: "textScore" } });

This will give a result like this:

{
    "_id" : ObjectId("5e8237b3c3ff893c44edd74e"),
    "name" : {
        "en" : "Frodo Baggins",
        "ru" : "Фродо Беггинс"
    },
    "score" : 1.5
},
{
    "_id" : ObjectId("5e8237b3c3ff893c44edd74f"),
    "name" : {
        "en" : "Bilbo Baggins",
        "ru" : "Бильбо Беггинс"
    },
    "score" : 0.75
}

Upvotes: 2

Related Questions