Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 312
Jessie Avatar asked Aug 30 '12 06:08

Jessie


People also ask

How do I stop MongoDB from inserting duplicate records?

To insert records in MongoDB and avoid duplicates, use “unique:true”.

How do I get distinct records in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.


1 Answers

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)); 
like image 155
theon Avatar answered Sep 27 '22 19:09

theon