2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Mongodb avoid duplicate entries

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?

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

// everyone's username must be unique:


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

MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.

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.ensureIndex({email:1},{unique:true, sparse:true});

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

BasicDBObject query = new BasicDBObject("email", 1).append("unique", "true");


Answer is