Reputation: 591
For example I have the following structure of documents:
{
"subject":"Joe owns a dog",
"content":"Dogs are man's best friend",
"likes": 60,
"year":2015,
"language":"english"
}
And the schema would be:
var schema = new Schema({
subject: {type: String},
content: {type: String},
likes: {type: int},
year: {type: int},
language: {type: String}
}
schema.createIndex({"subject": "text"});
Can I dynamically remove the index and create another one with more fields?
So if now it searches for a keyword in subject field, I would like to change it dynamically and search in "subject" and "content". to change to:
schema.createIndex({"subject": "text", "content": "text"});
Do you think that is possible?
Thanks a lot.
Upvotes: 4
Views: 6118
Reputation: 23515
The answer is yes, you can build dynamically indexes.
Using ensureIndex(...);
mongoDB function.
To remove the index use dropIndexes(...);
mongoDB function.
But I'm warning you, manipulating indexes is a major action, that's gonna have major impact on performances depending on the size of your collection.
By default mongoDB create indexes using foreground method, take a look at what mongoDB says about it:
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
So if you want really create indexes dynamically, maybe you should consider to make mongoDB to create index in background:
For potentially long running index building operations, consider the background operation so that the MongoDB database remains available during the index building operation.
Here is full mongoDB documentation about Indexes
ensureIndex(...) documentation
dropIndexes(...) documentation
How to call directly mongoDB methods from mongoose
Upvotes: 9