Update : this question was asked regarding MongoDB 1.8.x, and the decision made relates to 1.8. Please note, however, that Mongo 2.x has made changes to the error messages so that you can determine which fields generate errors in the update, as well as insert (see Kyle and Remon comments below).
Is there a way to try Mongo upsert and, if there is a unique index violation, to know which field is causing the problem - all in one database operation?
For example, let's say I have a customers collection with _id and name properties. Furthermore, let's say a unique index exists for name to ensure that two two customer docs do not have the same name .
I am currently doing two database operations to do upsert:
- Request
customers to find out if there is a document with the name that I am going to insert / update. - Eliminate if the conflict does not exist.
I would like to be able to do this in one operation and, if there is an error, to know which field is causing the problem.
This is possible if the operation is to create a new document. Mongo returns an E11000 duplicate key error index: {index name} . This is a bit of a hack, but I can use a regex to parse the index name (which in my case has a field name in it).
However, when updating a document, the error message does not contain information about the index or field. It is simply " E11001 duplicate key on update ".
Does anyone else have suggestions on clever ways to use upserts and know which fields cause unique index problems if necessary? Hope that stores JavaScript functions on the server side ...
source share