Home > Net >  How to Create MongoDB Atlas Search Index on a Nested String
How to Create MongoDB Atlas Search Index on a Nested String

Time:10-29

I'm trying to create an Autocomplete UI for my frontend. As a result I'm running the following query:

    return Product.find({ 'data.text': { '$regex': `${searchTerm}`, '$options': 'i' } }).limit(200);

Unfortunately, the above query is so so slow.

After digging around, I was advised to use MongoDb Atlas Search Index to speed up my queries.

My product schema is of the form

{
  ...,
  data: Object //Can contain any key value pair one of which is text as used above
}

Creating a regular Atlas Search Index has been straightforward like

{
  "mappings": {
    "dynamic": false,
    "fields":[
      "name":{
        type:"string"
     }
    ]
  }
}

But how can I create a nested Search Index for my above use case. I would like to index 'data.text' only

CodePudding user response:

You can create an index on a nested field using: db.collection('...').ensureIndex("data.text": 1)

Or

{
  "mappings": {
    "dynamic": false,
    "fields":[
      "data.text":{
        type:"string"
     }
    ]
  }
}
  • Related