8

I am using a java program for mongo db insertion trying to create a unique index for a field. product_src is a field in my collection and I want to set it as unique index for avoiding the duplicate insertion. 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. there is problem with line db.t.ensureIndex({"product_src":1});

Please give me a sample code how to create unique index in mongo DB

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
sarath
  • 455
  • 1
  • 11
  • 26
  • What is the exact problem at line db.t.ensureIndex({"product_src":1});? Looking at this line it should be t.ensureIndex({"product_src":1}); – Prashant Thakkar Dec 31 '14 at 10:44
  • syntax error on tockens, delete this tockens and red underline under this ({"product_src":1}) and also under t – sarath Dec 31 '14 at 10:51

2 Answers2

16

For future reference, the way to handle this in the Java Mongo driver v3.0+ is by:

public void createUniqueIndex() {
    Document index = new Document("field", 1);
    MongoCollection<Document> collection = client.getDatabase("db").getCollection("Collection");
    collection.createIndex(index, new IndexOptions().unique(true));
}
Cuga
  • 17,668
  • 31
  • 111
  • 166
  • As an addition to the reply, this will add ascending index on field as the second parameter is 1. If you want the index to be created in descending order, you need to do this: `Document index = new Document("field", -1);` – GokcenG Apr 08 '19 at 13:46
7

You need to pass a DBObject to the ensureIndex() method.

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.

db.t.createIndex(new BasicDBObject("product_src",1));
BatScream
  • 19,260
  • 4
  • 52
  • 68