【问题标题】:Can I add index dynamically to my schema in Mongoose?我可以在 Mongoose 中动态地将索引添加到我的模式吗?
【发布时间】:2017-04-07 10:42:57
【问题描述】:

例如,我有以下文档结构:

{
    "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"});

你认为这可能吗?

非常感谢。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

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

    使用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

    【讨论】:

    • 谢谢。然后我会尽量避免改变索引。
    猜你喜欢
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    相关资源
    最近更新 更多