Creating a unique index in mongoDB
I am using a java program to insert a mongo db while trying to create a unique index for a field. product_src is a field in my collection and I want to set it as a unique index to avoid duplicate insertion. I am trying the following code, but showing a 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 a collection. there is a problem with the db.t.ensureIndex ({"product_src": 1}) line;
Please give me some example code how to create a unique index in mongo DB
source to share
You need to pass DBObject
to the makeIndex () method .
db.t.ensureIndex(new BasicDBObject("product_src",1))
But the method has ensureIndex
been deprecated since version 2.12
, you need to use instead createIndex()
.
db.t.createIndex(new BasicDBObject("product_src",1));
source to share
For future reference, the way to handle this in the Java Mongo v3.0 + driver is as follows:
public void createUniqueIndex() {
Document index = new Document("field", 1);
MongoCollection<Document> collection = client.getDatabase("db").getCollection("Collection");
collection.createIndex(index, new IndexOptions().unique(true));
}
source to share