mongoose设置Partial Indexes
时间: 2023-07-04 19:10:51 浏览: 53
在Mongoose中设置Partial Indexes可以通过在Schema中使用`index`方法来实现。Partial Indexes是只针对符合特定查询条件的文档进行索引,而不是对整个集合进行索引,因此可以提高查询效率和减少索引存储空间。
以下是设置Partial Indexes的示例代码:
```javascript
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: {
type: String,
index: {
unique: true,
partialFilterExpression: { email: { $type: 'string' } }
}
},
age: {
type: Number,
index: {
partialFilterExpression: { age: { $gte: 18 } }
}
}
});
const User = mongoose.model('User', userSchema);
```
在上面的代码中,我们使用`index`方法设置了两个Partial Indexes,一个是针对`email`字段的唯一索引,只针对类型为字符串的文档进行索引;另一个是针对`age`字段的普通索引,只针对年龄大于等于18岁的文档进行索引。
需要注意的是,Partial Indexes只支持MongoDB 3.2及以上版本。