mongodb出现E11000 duplicate key error collection(id重复的解决办法)

解决mongodb id 重复问题
mongodb在插入数据时出现id重复错误,具体错误代码如下:

 { [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\') }' }


百度了一下,发现很多人都出现了类似问题,有人说手动删除自生成的id就能解决, 有人说清空集合就好了。 
结果是然并卵,数据库的id貌似是根据 时间戳+主机+进程号+序列生成的。重复的原因个人猜测可能有两种: 
内部原因: 同时插入两条数据,导致数据库生成了同一个id值。 
外部原因:每次使用同一个变量存储不同的数据,导致数据库认为每次存储的是同一条数据,最终生成同一个id值。

以上都有个共同点,就是让数据库自己生成id值。 
后来找到一篇stockoverflow中帖子,给了我启示.

 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.


大概意思是: 由于独特的约束,MongoDB只会允许一个文件,缺少索引字段。如果有一个以上的文档没有索引字段的值或缺少索引字段就会报错

于是自己手动添加id值,当插入的数据带有_id的字段时,mongodb就不再自动生成id。 
至此, mongodb重复id的问题就解决了。当然,肯定还有更好的解决办法,后续想到了再补充。

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值