How can I specify uniqueness in a multiple field in mongo NOT combined?

I have the following JSON scheme in MongoDB:

{"email": " example@gmail.com ", "second_email": " example222@gmil.com "} 

How can I ensure that both fields are unique separately and also unique between them.

Otherwise, the following document will be invalid:

 {"email":" anotherone@gmail.com ", "second_email":" example@gmail.com "} 

Because example@gmail.com already exists in another document in another field.

+6
source share
3 answers

No database can do this on top of my head (use a different column / field as input to limit uniqueness). To do this, you will need to do some data tuning. The easiest way is a unique constraint on the array field.

 > db.foo.createIndex({ emails: 1 }, { unique: true } ) > db.foo.insert({ emails: [' example@gmail.com ', ' example222@gmail.com '] }) WriteResult({ "nInserted" : 1 }) > db.foo.insert({ emails: [' anotherone@gmail.com ', ' example@gmail.com '] }) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error index: test.foo.$emails_1 dup key: { : \" example@gmail.com \" }" } }) 

Now, depending on your application logic, this array of email addresses may even replace the original two fields. Or not. You decide. If not, you need to insert both the original fields and duplicate them in this array to verify uniqueness.

+6
source

You need to create a unique index for each field to ensure uniqueness for the fields.

 db.collection.createIndex( { "email": 1 }, { "unique": true } ) db.collection.createIndex( { "second_email": 1 }, { "unique": true } ) 

Therefore, MongoDB does not provide a way to ensure uniqueness for two fields in the same documents. This is what you will need to do in your application using the if / else statement.

Another option, as shown in this answer here , is to use a field with an indexed array if you don't want to call createIndex() multiple times. But you still need to use logical condition processing if you do not want to duplicate the value in the array.

0
source
 db.collection.createIndex( { "mails.email": 1, "mails.second_email": 1 }, { unique: true } ) db.collection.insert( { _id: 3, mails: [ { email: " example@gmail.com ", second_email: " example222@gmil.com " } ] } ) 

You have now created a combination of email - second email pairs to ensure the uniqueness of these two fields.

In addition, if you use the mass option, you can set the order value to false to continue with the remaining inserts in the event of a failure. InsertMany ({}, {order: false})

0
source

All Articles