Mongodb 避免重复条目

新手上路,请多包涵

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

原文由 Jessie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 566
2 个回答

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

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

您也可以跨多个字段执行此操作。有关更多详细信息和示例, _请参阅文档中的 此部分_。

唯一索引确保索引字段不存储重复值;即强制索引字段的唯一性。默认情况下,MongoDB 在创建集合期间在 _id 字段上创建唯一索引。

如果您希望从唯一键中忽略 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));

原文由 theon 发布,翻译遵循 CC BY-SA 4.0 许可协议

从 Mongo 的 v3.0 Java 驱动程序开始,创建索引的代码如下所示:

 public void createUniqueIndex() {
    Document index = new Document("fieldName", 1);
    MongoCollection<Document> collection = client.getDatabase("dbName").getCollection("CollectionName");
    collection.createIndex(index, new IndexOptions().unique(true));
}

// And test to verify it works as expected
@Test
public void testIndex() {
    MongoCollection<Document> collection = client.getDatabase("dbName").getCollection("CollectionName");

    Document newDoc = new Document("fieldName", "duplicateValue");
    collection.insertOne(newDoc);

    // this will throw a MongoWriteException
    try {
        collection.insertOne(newDoc);
        fail("Should have thrown a mongo write exception due to duplicate key");
    } catch (MongoWriteException e) {
        assertTrue(e.getMessage().contains("duplicate key"));
    }
}

原文由 Cuga 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题