Can I add index dynamically to my schema in Mongoose?

无人久伴 提交于 2020-05-16 03:28:10

问题


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.


回答1:


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

getIndexes(...) documentation

How to call directly mongoDB methods from mongoose



来源:https://stackoverflow.com/questions/40764190/can-i-add-index-dynamically-to-my-schema-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!