I just got a weird error sent through from our application: it was
complaining of a duplicate key error on a collection with a unique index
on it, but the operation in question was an upsert, with the query part
matching a document by that unique key. I'd have expected that if the
key already existed that it would have just done an update, rather than
an insert.
Mongo 1.6.5, via the pymongo connector.
The exception is as follows:
DuplicateKeyError: E11000 duplicate key error index:
whereoscope.userDevices.$deviceId_1 dup key: { : "xxxxxxxx" }
And the line of code that triggered it was this:
res = self.db.userDevices.update({ 'deviceId' : deviceId }, { '$set'
: { key : deviceDetails } }, upsert=True, multiple=False, safe=True)
Some of the names above have been changed to protect the innocent. 'key'
above is one of handful of vanilla looking strings, notably not
'deviceId'. We are using replica sets, but that query was sent to the
master (we send all writes to the master, only do reads from slaves).
Any thoughts on what could be going wrong here?
Cheers,
James.
--
See where your kids are: http://whereoscope.com
Do you have any other unique indexes?
> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mongodb-user?hl=en.
>
>
James.
If all you are doing is querying the _id field and replacing/inserting
the new doc you can use save.
If your first example you were using "deviceId" and that would make
sense as a point of duplicate key failure if your query isn't just the
_id.
Can you post your full code where you are setting the values and
calling update/save? So far you have only posted pieces without
connecting sections. Also, I would suggest catching the duplicate
exception and logging the update operation, and the params; that will
give us a much better idea of what is going on.
I don't see anything (obviously) wrong either.
This can be re-written as users.save(userMod); It shouldn't make a
difference, since save just checks for the _id value and does an
update w/upsert like you are, but it does read better and is less code
for you to write.
Getting that logging/debug output would help a lot :)