I have a collection with fields "email" and "friends_email". I would like to setup a unique-ness constraint like the following, using MongoDB:
No record will have the same value for email and friends_email. So this would be invalid:
{"email": "[email protected]", "friends_email": "[email protected]" }
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?
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With