MongoDB show duplicate key is null?

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:

"errmsg" : "E11000 duplicate key error collection: testdb.setup index: name dup key: { : null }",

In your example, the collection setup in database testdb has a unique index on the name field. The attempted upsert failed because the name field was missing and there was already a document in this collection with a missing or null value for name.

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:

    db.setup.createIndex(
        {name: 1},
        {unique:true, sparse:true}
    )
    
  • Drop and recreate the unique index using a partial filter expression (which allows further criteria if needed):

    db.setup.createIndex(
       { name: 1},
       { unique:true, partialFilterExpression: {name: {$exists:true }}}
    )
    

Tags:

Mongodb