node.js - 我可以动态地将索引添加到 Mongoose 中的架构中吗?

标签 node.js mongodb mongoose mongodb-query

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

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

你认为这可能吗?

非常感谢。

最佳答案

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

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

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

<小时/>

但我警告您,操作索引是一项重大操作,这会对性能产生重大影响,具体取决于您的集合的大小。

mongoDB默认使用前台方法创建索引,看看mongoDB是怎么说的:

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 在后台创建索引:

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

关于node.js - 我可以动态地将索引添加到 Mongoose 中的架构中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764190/

相关文章:

json - API 设计 : Which is better: returning null for empty values or nothing

node.js - Mongoose 架构错误 : "Cast to string failed for value" when pushing object to empty array

arrays - 如何从 Mongoose 数组中获取数据?

node.js - MongoDB。如何将文档从一个数组移动到另一个数组?

javascript - 我应该从 Node.js Express 返回回调吗?

node.js - bash:npm:在 cPanel 终端中找不到命令

php - PHP 中的 Mongodb MapReduce

javascript - 从 javascript Node.js 调用 mongoexport

javascript - Puppeteer 无法获得完整的源代码

javascript - 使用 JavaScript 忽略 "a"、 "the"等的字符串搜索