Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating unique index in mongoDB

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

like image 390
sarath Avatar asked Dec 31 '14 10:12

sarath


People also ask

How do I create a unique compound index in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

How do I make a document unique in MongoDB?

Unique Constraint in MongoDB will allow only a single document with the same value for the indexed key. If we attempt to insert the same value for a single indexed key, it will result in an error. This returns every document in the collection. This is an attempt to insert a record with the same code.

How indexes are created in MongoDB?

Indexes can be created by using the createIndex method. Indexes can be created on just one field or multiple field values. Indexes can be found by using the getIndexes method. Indexes can be removed by using the dropIndex for single indexes or dropIndexes for dropping all indexes.


2 Answers

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));
}
like image 157
Cuga Avatar answered Oct 29 '22 06:10

Cuga


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));
like image 30
BatScream Avatar answered Oct 29 '22 07:10

BatScream