2016-11-23 55 views
1

比如我的文档结构如下:我可以将索引动态添加到Mongoose中的模式中吗?

{ 
    "subject":"Joe owns a dog", 
    "content":"Dogs are man's best friend", 
    "likes": 60, 
    "year":2015, 
    "language":"english" 
} 

和模式将是:

var schema = new Schema({ 
    subject: {type: String}, 
    content: {type: String}, 
    likes: {type: int}, 
    year: {type: int}, 
    language: {type: String} 
} 

schema.createIndex({"subject": "text"}); 

我可以动态地删除索引,并创建另一个更多的领域?

因此,如果现在它在主题字段中搜索关键字,我想动态地更改它并在“主题”和“内容”中进行搜索。改成:

schema.createIndex({"subject": "text", "content": "text"}); 

你认为这是可能的吗?

非常感谢。

回答

4

答案是肯定的,你可以建立动态索引。

使用ensureIndex(...); mongoDB函数。

删除索引使用dropIndexes(...); mongoDB函数。


但我警告你,操纵索引是一个重大的行动,这将对性能产生重大影响,具体取决于你的收藏大小。

默认情况下,MongoDB的使用前景方法来创建索引,看看什么MongoDB的说一下吧:

默认情况下, 数据库上创建索引块的所有其他操作。当一个集合建立索引,即 保存收集的数据库是无法进行读或写,直到 索引构建完成

所以,操作,如果你想真正的动态创建索引,也许你应该考虑清楚的MongoDB在后台创建索引:

潜在的长时间运行的索引构建操作,请考虑 后台操作,使MongoDB的数据库索引构建操作过程中仍然可用 。

Here is full mongoDB documentation about Indexes


ensureIndex(...) documentation

dropIndexes(...) documentation

getIndexes(...) documentation

How to call directly mongoDB methods from mongoose

+1

感谢。然后我会尽量避免改变索引。 – Octtavius

相关问题