【发布时间】:2012-08-24 20:28:14
【问题描述】:
我是 mongodb 的新手。我可以知道如何避免重复条目。在关系表中,我们使用主键来避免它。我可以知道如何在 Mongodb 中使用 java 指定它吗?
【问题讨论】:
标签: java mongodb mongodb-java
我是 mongodb 的新手。我可以知道如何避免重复条目。在关系表中,我们使用主键来避免它。我可以知道如何在 Mongodb 中使用 java 指定它吗?
【问题讨论】:
标签: java mongodb mongodb-java
我不是 Java 程序员,但是您可以将其转换过来。
默认情况下,MongoDB 确实有一个称为 _id 的主键,您可以在此键上使用 upsert() 或 save() 以防止文档被写入两次:
var doc = {'name': 'sam'};
db.users.insert(doc); // doc will get an _id assigned to it
db.users.insert(doc); // Will fail since it already exists
这将立即停止重复。至于某些条件下的多线程安全插入:好吧,在这种情况下,我们需要更多地了解您的情况。
我应该补充一点,_id 索引默认情况下是 unqiue。
【讨论】:
使用带有{unique:true} 选项的索引。
// everyone's username must be unique:
db.users.createIndex({email:1},{unique:true});
您也可以跨多个字段执行此操作。 有关更多详细信息和示例,请参阅文档中的 this section。
唯一索引确保索引字段不存储重复值;即强制索引字段的唯一性。默认情况下,MongoDB 在创建集合期间会在 _id 字段上创建唯一索引。
如果您希望从唯一键中忽略 null 值,那么您还必须通过添加 sparse 选项来使索引稀疏(参见 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));
【讨论】:
null 并且不存在也算作唯一值,因此如果您有一个用户表,其中一些已删除并且根据法律您删除他们的数据但保留他们的行以供将来删除,您将遇到问题具有唯一索引。我想这是真的需要。
Theon 解决方案对我不起作用,但这个解决方案对我有用:
BasicDBObject query = new BasicDBObject(<fieldname>, 1);
collection.ensureIndex(query, <index_name>, true);
【讨论】:
这可以使用“_id”字段来完成,尽管不鼓励使用。 假设您希望名称是唯一的,那么您可以将名称放在“_id”列中,并且您可能知道“_id”列对于每个条目都是唯一的。
BasicDBObject bdbo = new BasicDBObject("_id","amit");
现在,集合中没有其他条目可以将名称命名为“amit”。这可能是您要求的方式之一。
【讨论】:
在 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"));
}
}
【讨论】:
使用 pymongo 它看起来像:
mycol.create_index("id", unique=True)
其中 myCol 是数据库中的集合
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.create_index("id", unique=True)
mydict = {"name": "xoce", "address": "Highway to hell 666", "id": 1}
x = mycol.insert_one(mydict)
【讨论】: