E11000 duplicate key error collection in mongodb


id repetition error occurs when mongodb is inserting data. The specific error code is as follows:

 { [MongoError: E11000 duplicate key error collection: zhihu.people index: _id_ dup key: { : ObjectId('59a3b9275f063c20cc8bdec7') }]
  name: 'MongoError',
  message: 'E11000 duplicate key error collection: zhihu.people index: _id_ dup key: { : ObjectId(\'59a3b9275f063c20cc8bdec7\') }',
  driver: true,
  index: 0,
  code: 11000,
  errmsg: 'E11000 duplicate key error collection: zhihu.people index: _id_ dup key: { : ObjectId(\'59a3b9275f063c20cc8bdec7\') }' }

baidu once, found that many people have a similar problem, some people say that since removed manually generated id can solve, someone says to empty the collection.
turns out to be useless, however, as the database id appears to be generated based on the timestamp + host + process + sequence. There are two possible reasons for the repetition:
internal reasons: insert two pieces of data at the same time, causing the database to generate the same id value.
external reason: using the same variable to store different data each time causes the database to think that it stores the same data each time and finally generates the same id value.
All of the above have one thing in common: let the database generate the ID value itself.
then found a post on stockoverflow that gave me the hint.

 If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.

You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.

: due to unique constraints, MongoDB will only allow one file, missing index fields. An error is reported if more than one document does not have the value of an index field or is missing an index field
Add the ID value yourself manually, and mongoDB will no longer automatically generate the ID when the inserted data has a field of _ID.
so far, the mongodb duplicate id problem is solved. Of course, there must be a better solution, I think of a follow-up to add.

Read More: