Suppose this is a document representing a customer.
{ company_name: 'corporate ltd.', pocs: [ {name: 'Paul', email: ' paul@corporate.com '}, {name: 'Jessica', email: ' jessica@corporate.com '} ] }
I would like to define a unique index for pocs.email
so I issued the following command:
db.things.ensureIndex({"pocs.email": 1}, {unique: true})
The strange thing is that when you try to add another company with a poc that has an email already exists in another company, mongo rejects this, observing the unique index constraint.
that is, the following cannot exist:
{ company_name: 'corporate ltd.', pocs: [ {name: 'Paul', email: ' paul@corporate.com '}, {name: 'Jessica', email: ' jessica@corporate.com '} ] }, { company_name: 'contoso llc', pocs: [ {name: 'Paul', email: ' paul@corporate.com '}, ] }
This is normal. However, duplication of poc within one document is possible, for example,
{ company_name: 'corporate ltd.', pocs: [ {name: 'Paul', email: ' paul@corporate.com '}, {name: 'Paul', email: ' paul@corporate.com '}, {name: 'Jessica', email: ' jessica@corporate.com '} ] },
see the sequence of my cli commands below:
> version() version: 2.0.2 > > use test switched to db test > db.test.ensureIndex({"poc.email": 1}, {unique: true}) > > db.test.insert({company: "contoso", poc: [{email: ' me@comapny.com '}]}) > db.test.insert({company: "contoso", poc: [{email: ' me@comapny.com '}]}) E11000 duplicate key error index: test.test.$poc.email_1 dup key: { : " me@comapny.com " } > ({company: "contoso", poc: [{email: ' me.too@comapny.com '}, {email: ' me.too@company.com '}]}) > > > db.test.find() { "_id" : ObjectId("4f44949685926af0ecf9295d"), "company" : "contoso", "poc" : [ { "email" : " me@comapny.com " } ] } { "_id" : ObjectId("4f4494b885926af0ecf9295f"), "company" : "contoso", "poc" : [ { "email" : " me.too@comapny.com " }, { "email" : " me.too@company.com " } ] }
In addition, this happens either during insert
or in update
.
> db.test.update({"_id" : ObjectId("4f44949685926af0ecf9295d")}, {$push: { poc: {email: ' me@company.com '}}}) > db.test.find() { "_id" : ObjectId("4f4494b885926af0ecf9295f"), "company" : "contoso", "poc" : [ { "email" : " me.too@comapny.com " }, { "email" : " me.too@company.com " } ] } { "_id" : ObjectId("4f44949685926af0ecf9295d"), "company" : "contoso", "poc" : [ { "email" : " me@comapny.com " }, { "email" : " me@company.com " }, { "email" : " me@company.com " } ] } >
Is this a mistake or by design I skipped the definition in the documentation?