我可以在Mongoose中动态添加索引到我的架构吗? [英] Can I add index dynamically to my schema in Mongoose?

查看:184
本文介绍了我可以在Mongoose中动态添加索引到我的架构吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"
}

模式将是:

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

您认为有可能吗?

非常感谢.

推荐答案

是的,您可以动态创建索引.

The answer is yes, you can build dynamically indexes.

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

Using ensureIndex(...); mongoDB function.

要删除索引,请使用dropIndexes(...); mongoDB函数.

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.

默认情况下,mongoDB使用前景方法创建索引,看看mongoDB对此有何评论:

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

因此,如果您想真正地动态创建索引,也许应该考虑使mongoDB在后台创建索引:

So if you want really create indexes dynamically, maybe you should consider to make mongoDB to create index in background:

对于可能长期运行的索引构建操作,请考虑 后台操作,以便MongoDB数据库保持可用 在建立索引过程中.

For potentially long running index building operations, consider the background operation so that the MongoDB database remains available during the index building operation.

此处是有关索引的完整mongoDB文档

ensureIndex(...)文档

dropIndexes(...)文档

getIndexes(...)文档

如何直接从猫鼬调用mongoDB方法

这篇关于我可以在Mongoose中动态添加索引到我的架构吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆