How to dynamically change the text index in mongodb for a single collection?

276 views Asked by At

Is it possible to change the text index search dynamically on a single collection on mongodb? I originally have a $text index on the first.text field of my collection, but when the user presses a button, I want to switch over to only allow the text search to be done on the second.text field. I am aware that only one text index can be created on a mongodb collection at a time.

Here is an example of what my collection schema looks like for simplicity, I just want to get feedback on if it's possible to change dynamically without giving up any cost for performance:

{
    first : {
        text : 'search here'
    },
    second : {
        text : 'search ONLY here after a button press'
    },
}
1

There are 1 answers

0
arash maleki On

you can make on_pre_GET hook and use ensureIndex(...) to make your index or drop index using dropIndexes(...)

but manipulating indexes is a major action and it has huge cost on performance. mongoDb says:

By default, creating an index blocks all other operations on a database. When building an index on a collection, the database that holds the collection is unavailable for read or write operations until the index build completes

you can make REGULAR index on each field and use $regex like:

?where={"first.text": {"$regex": ".*search.*"}}