Mongodb avoid duplicate entries

Jessie picture Jessie · Aug 30, 2012 · Viewed 37.9k times · Source

I am newbie to mongodb. May I know how to avoid duplicate entries. In relational tables, we use primary key to avoid it. May I know how to specify it in Mongodb using java?

Answer

theon picture theon · Aug 30, 2012

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