我是 mongodb 的新手。我可以知道如何避免重复条目。在关系表中,我们使用主键来避免它。我可以知道如何使用 java 在 Mongodb 中指定它吗?
7 回答
使用带有{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));
这可以使用“_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"));
}
}
我不是 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 的。
Theon 解决方案对我不起作用,但这个解决方案确实有效:
BasicDBObject query = new BasicDBObject(<fieldname>, 1);
collection.ensureIndex(query, <index_name>, true);
使用 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)
防止 mongoDB 保存重复的电子邮件
UserSchema.path('email').validate(async(email)=>{
const emailcount = await mongoose.models.User.countDocuments({email})
return !emailcount
}, 'Email already exits')
可以帮助你的问题......对我有用......在用户模型中使用。 参考解释 谢谢...