在
{unique:true}选项中使用索引。// everyone's username must be unique:db.users.createIndex({email:1},{unique:true});您也可以跨多个字段执行此操作。 有关 更多详细信息和示例, 请参阅 文档中的
此部分 。
MongoDB索引可以有选择地施加一个 唯一的键约束 ,以确保不会插入任何索引键值与现有文档值匹配的文档。
如果希望
null从唯一键中忽略值,那么还必须通过添加以下选项来使索引稀疏( 请参见
此处)
sparse:
// everyone's username must be unique,//but there can be multiple users with no email field or a null email:db.users.createIndex({email:1},{unique:true, sparse:true});如果要使用MongoDB Java驱动程序创建索引。尝试:
document keys = new document("email", 1);collection.createIndex(keys, new IndexOptions().unique(true));


