Mongodb avoid duplicate entries Mongodb avoid duplicate entries mongodb mongodb

Mongodb avoid duplicate entries


Use an index with the {unique:true} option.

// everyone's username must be unique:db.users.createIndex({email:1},{unique:true});

You can also do this across multiple fields. See this section in the docs for more details and examples.

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.

If you wish for null values to be ignored from the unique key, then you have to also make the index sparse (see here), by also adding the sparse option:

// 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});

If you want to create the index using the MongoDB Java Driver. Try:

Document keys = new Document("email", 1);collection.createIndex(keys, new IndexOptions().unique(true));


This can be done using "_id" field although this use is discouraged.suppose you want the names to be unique, then you can put the names in "_id" column and as you might know "_id" column is unique for each entry.

BasicDBObject bdbo = new BasicDBObject("_id","amit");

Now , no other entry can have name as "amit" in the collection.This can be one of the way you are asking for.


As of Mongo's v3.0 Java driver, the code to create the index looks like:

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@Testpublic 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"));    }}