Nedb db.ensureIndex()

2018-07-11 19:26 更新

db.ensureIndex(options, callback)

作用:

NeDB支持索引。索引可以提高查询速度以及保证字段的唯一性。索引可以用在任何字段,包括嵌套很深的字段。目前,索引只能用来加速基本查询以及使用$in, $lt, $lte, $gt 和 $gte运算符的查询,如上find接口中示例所示。保证索引不为数组对象。方法可以在任何时候被调用,推荐在应用启动时就调用(该方法是同步的,为1000个文档添加索引仅需35ms)。

参数:

fieldName(必须): 索引字段,使用“.”给嵌套的字段加索引。

unique(可选,默认false): 字段唯一性约束。注意:唯一性约束会增加为两个文档中没有定义的字段添加索引的错误。

sparse(可选,默认false): 不能为没有定义的字段加索引。如果接受给多个文档中没有定义的字段添加索引,给需要该配置参数与unique一起使用。

expireAfterSeconds(可选,秒数): TTL索引,设置自动过期时间。

删除索引: db.removeIndex(fieldName, cb)

注意:_id字段会自动加索引和唯一性约束,不必再为它使用ensureIndex。如果使用本地存储,索引也将保存在数据文件中,当第二次加载数据库时,索引也将自动被添加。如果加载一个已经有索引的数据库,删除索引将不起任何作用。

示例

db.ensureIndex({ fieldName: 'somefield' }, function (err) {
  // If there was an error, err is not null
});
 
// 对索引设置唯一性约束
db.ensureIndex({ fieldName: 'somefield', unique: true }, function (err) {
});
 
// Using a sparse unique index
db.ensureIndex({ fieldName: 'somefield', unique: true, sparse: true }, function (err) {
});
 
 
// 使用唯一性约束制造错误,查看err的格式
db.insert({ somefield: 'nedb' }, function (err) {
  // err is null
  db.insert({ somefield: 'nedb' }, function (err) {
    // err is { errorType: 'uniqueViolated'
    //        , key: 'name'
    //        , message: 'Unique constraint violated for key name' }
  });
});
 
// 移除somefield字段的索引
db.removeIndex('somefield', function (err) {
});
 
// Example of using expireAfterSeconds to remove documents 1 hour
// after their creation (db's timestampData option is true here)
db.ensureIndex({ fieldName: 'createdAt', expireAfterSeconds: 3600 }, function (err) {
});
 
// You can also use the option to set an expiration date like so
db.ensureIndex({ fieldName: 'expirationDate', expireAfterSeconds: 0 }, function (err) {
  // Now all documents will expire when system time reaches the date in their
  // expirationDate field
});


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号