MongoDB version 3.6
I got the duplicate key message when I executed this. What's the actual problem?
mongos> db.setup.findAndModify({
... query : {"_id" : ObjectId("5b3c7abbea95705803084cad")},
... update : {$set : { "test" : "xxxx" }},
... upsert : true
... })
2018-07-06T10:13:22.749+0000 E QUERY [thread1] Error: findAndModifyFailed failed: {
"ok" : 0,
"errmsg" : "E11000 duplicate key error collection: testdb.setup index: name dup key: { : null }",
"code" : 11000,
"codeName" : "DuplicateKey",
"$clusterTime" : {
"clusterTime" : Timestamp(1530872002, 603),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
},
"operationTime" : Timestamp(1530872002, 602)
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCollection.prototype.findAndModify@src/mongo/shell/collection.js:724:1
@(shell):1:1
mongos>
Best Answer
This is the expected case if you have defined a unique index which is non-sparse: documents missing a value for the field with the unique index will have an indexed value of
null
. This means that only a single document in the collection can be missing the unique field.The duplicate key message includes the index name and key violation:
In your example, the collection
setup
in databasetestdb
has a unique index on thename
field. The attempted upsert failed because thename
field was missing and there was already a document in this collection with a missing ornull
value forname
.If you want to use a unique index without requiring the field to be present you have a few options:
Drop and recreate the unique index with the
sparse
property:Drop and recreate the unique index using a partial filter expression (which allows further criteria if needed):