Mongodb避免重复输入

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

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

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

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

MongoDB索引可以选择强制使用唯一键约束 ,这可以保证不会插入任何文档,其索引键的值与现有文档的值相匹配。

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

这可以使用“_id”字段来完成,但不鼓励使用“_id”字段。 假设您希望名称是唯一的,那么您可以将名称放在“_id”列中,因为您可能知道“_id”列对于每个条目都是唯一的。

 BasicDBObject bdbo = new BasicDBObject("_id","amit"); 

现在,没有其他条目可以在集合中具有名称“amit”。这可能是您要求的方式之一。

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

 public void createUniqueIndex() { Document index = new Document("fieldName", 1); MongoCollection 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 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")); } } 

Theon解决方案对我不起作用,但是这个解决了:

 BasicDBObject query = new BasicDBObject(, 1); collection.ensureIndex(query, , true); 

我不是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 

这将立即停止重复。 对于在某些条件下的multithreading安全插入:在这种情况下,我们需要更多地了解您的情况。

我应该补充一点,默认情况下_id索引是unqiue。