我是 mongodb 的新手。我可以知道如何避免重复条目吗?在关系表中,我们使用主键来避免它。我可以知道如何使用 java 在 Mongodb 中指定它吗?
原文由 Jessie 发布,翻译遵循 CC BY-SA 4.0 许可协议
我是 mongodb 的新手。我可以知道如何避免重复条目吗?在关系表中,我们使用主键来避免它。我可以知道如何使用 java 在 Mongodb 中指定它吗?
原文由 Jessie 发布,翻译遵循 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 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
3 回答1.7k 阅读✓ 已解决
使用带有
{unique:true}
选项的索引。您也可以跨多个字段执行此操作。有关更多详细信息和示例, _请参阅文档中的 此部分_。
如果您希望从唯一键中忽略
null
值,那么您还必须通过添加sparse
选项来使索引稀疏( _参见 此处_):如果要使用 MongoDB Java 驱动程序创建索引。尝试: