[英]creating unique index in mongoDB
I am using a java program for mongo db insertion trying to create a unique index for a field. 我正在使用java程序进行mongo db插入尝试为字段创建唯一索引。 product_src is a field in my collection and I want to set it as unique index for avoiding the duplicate insertion.
product_src是我的集合中的一个字段,我想将其设置为唯一索引,以避免重复插入。 I am trying the following code but showing syntax error what is the problem with this.
我正在尝试以下代码,但显示语法错误这是什么问题。
DB db;
try {
sample = new MongoClient("myIP",PORT);
db = sample.getDB("client_mahout");
t = db.getCollection("data_flipkart_in_avoid_duplicate_checking");
System.out.println("enter the system ip");
db.t.ensureIndex({"product_src":1});
} catch (Exception e) {}
t is the collection. t是集合。 there is problem with line db.t.ensureIndex({"product_src":1});
行db.t.ensureIndex({“product_src”:1})存在问题;
Please give me a sample code how to create unique index in mongo DB 请给我一个示例代码,如何在mongo DB中创建唯一索引
For future reference, the way to handle this in the Java Mongo driver v3.0+ is by: 为了将来参考,在Java Mongo驱动程序v3.0 +中处理此问题的方法是:
public void createUniqueIndex() {
Document index = new Document("field", 1);
MongoCollection<Document> collection = client.getDatabase("db").getCollection("Collection");
collection.createIndex(index, new IndexOptions().unique(true));
}
You need to pass a DBObject
to the ensureIndex() method. 您需要将
DBObject
传递给ensureIndex()方法。
db.t.ensureIndex(new BasicDBObject("product_src",1))
But, the ensureIndex
method has been deprecated since version 2.12
, you need to use createIndex()
instead. 但是,自
2.12
版以来不推荐使用 ensureIndex
方法,您需要使用createIndex()
。
db.t.createIndex(new BasicDBObject("product_src",1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.