java - Mongodb避免重复条目

我是 mongodb 的新手。我可以知道如何避免重复条目。在关系表中,我们使用主键来避免它。我可以知道如何在 Mongodb 中使用 java 指定它吗?

最佳答案

使用带有 {unique:true} 选项的索引。

// everyone's username must be unique:
db.users.createIndex({email:1},{unique:true});

您也可以跨多个字段执行此操作。 见 this section 在文档中了解更多详细信息和示例。

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.

如果您希望从唯一键中忽略 null 值,那么您还必须使索引稀疏(参见 here ),同时添加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));

https://stackoverflow.com/questions/12191311/

相关文章:

javascript - MongoError,错误 :E11000 duplicate key e

mongodb - 寻找 1 x 100 万个交叉点的最佳解决方案? Redis、Mongo、其他

java - 编码对象时未使用 MongoDB BSON 编解码器

mongodb - 如何在 MongoDB 中将子文档展平为根级别?

mongodb - MongoDB中聚合($match)和查找之间的区别?

mongodb - mongoengine - 忽略模式验证的额外字段

node.js - 模拟/测试 Mongodb 数据库 Node.js

mongodb - 使用 mongodb 或 cassandra 的空间数据

mongodb - 使用 sphinx 搜索与 mongodb 作为数据源

java - 如何直接从 Java 中的 mongodb 查询返回原始 JSON?