索引属性 unique指定
比较重要的属性有:
名字 db.collection.ensureIndex({},{name:''}) 在创建索引时,mongodb会自己给索引创建默认的名字,这种名字并不好记,我们看一下mongodb是怎么给自己命名的 唯一性: 第二个属性,是索引的唯一性 db.collection.ensureIndex({},{unique:true/false}) 如果设置为true,表明这个索引为唯一索引,表示这个字段不能插入两个重复的数据 稀疏性: 是否定时删除:比如过期索引
唯一索引
> db.suoyin.ensureIndex({m:1,n:1},{unique:true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
指定一个唯一索引,然后插入一条数据
> db.suoyin.insert({m:1,n:2})
WriteResult({ "nInserted" : 1 })
再插入一条一样的
> db.suoyin.insert({m:1,n:2})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.suoyin index: m_1_n_1 dup key: { : 1.0, : 2.0 }"
}
})
报错了,因为设置了m,n为唯一索引,不能是重复插入,这可以实现mysql中的,如果已经存在不插入,如果不存在则插入

浙公网安备 33010602011771号