例如,我有以下文档结构:
{
"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
关于node.js - 我可以动态地将索引添加到 Mongoose 中的架构中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764190/