好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MongoDB中唯一索引(Unique)的那些事

写在前面 func init() { phoneIndex := mgo.Index{ Key: []string{"phone"}, Unique: true, } col := db.Collection(&User{}) col.EnsureIndex(phoneIndex) } type User struct { Email string `bson:"email"` Salt string `bson:"salt"` Phone string `bson:"phone,omitempty"` IDCard string `bson:"idcard"` RealName string `bson:"realname"` AuthStatus int `bson:"auth_status"` } index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. 解决方式

db.getCollection("test").createIndex( { "phone": 1 }, { sparse: true })

db.getCollection("test").createIndex( { "phone": 1 }, { sparse: true,unique: true } ) func init() { phoneIndex := mgo.Index{ Key: []string{"phone"}, Unique: true, Sparse: true, } col := db.Collection(&User{}) col.EnsureIndex(phoneIndex) } 总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对自学php网的支持。

查看更多关于MongoDB中唯一索引(Unique)的那些事的详细内容...

  阅读:78次