使用{unique:true}选项的索引。
// everyone's username must be unique:
db.users.createIndex({email:1},{unique:true});
您也可以在多个字段中执行此操作。有关详细信息和示例,请参阅文档中的this section。
MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.
如果希望从唯一键忽略空值,则还必须通过添加稀疏选项来使索引稀疏(参见here):
// 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));