Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique Constraint with Two Fields in MongoDB

Tags:

mongodb

I have a collection with fields "email" and "friends_email". I would like to setup a unique-ness constraint like the following, using MongoDB:

  1. No record will have the same value for email and friends_email. So this would be invalid:

    {"email": "[email protected]", "friends_email": "[email protected]" } 
  2. No 2 records will have the same values for all fields. So the following examples would ALL be invalid:

    {     { "email": "[email protected]", "friends_email": "[email protected]" },     { "email": "[email protected]", "friends_email": "[email protected]" } } {     { "email": "[email protected]", "friends_email": null },     { "email": "[email protected]", "friends_email": null } } {     { "email": null, "friends_email": "[email protected]" },     { "email": null, "friends_email": "[email protected]" } } 

    In plain english, it would be something like, the concatenation of email and friends_email will be unique, with null and undefined being coalesced into empty-string.

What's the best way to enforce this rule in MongoDB?

like image 928
Randy L Avatar asked Feb 04 '13 18:02

Randy L


People also ask

How do I set unique fields in MongoDB?

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

How do I search for multiple fields in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

What is ISODate in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

What is unique key 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.


1 Answers

It sounds like you need a compound unique index:

db.users.createIndex( { "email": 1, "friends_email": 1 }, { unique: true } ) 

... and you can verify at the ORM layer that email =/= friends_email.

like image 92
Winfield Avatar answered Sep 20 '22 21:09

Winfield