为什么DuplicateKeyError:E11000重复键错误索引:test.test.$ notification_1 dup键:{:null} [英] why DuplicateKeyError: E11000 duplicate key error index: test.test.$notification_1 dup key: { : null }

查看:827
本文介绍了为什么DuplicateKeyError:E11000重复键错误索引:test.test.$ notification_1 dup键:{:null}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样创建唯一索引:

self.db_database[co_name].ensure_index([('src_md5',-1),('src_time',-1),('src_size',-1)],unique=True)
self.db_database[co_name].ensure_index(('notification'),unique=True)
self.db_database[co_name].ensure_index(('version'),unique=True)`  

在插入之前,我将创建一条记录,如下所示:

before insert i creat a record as follows:

self.db_database[co_name].insert({"notification":"yes","file_md5":-1,"file_size":-1,"file_time":-1,"bypass":0,"server_list":[],"ok_to_download":0,"force_to_download":-1,"idx":0},safe=True)`  

然后我插入一些这样的信息:

then i insert some info like this:

collection.insert({"src_host":src_host,"src_path":src_path,"src_name":src_name,"src_md5":src_md5,"src_time":src_time,"src_size":src_size,"version":idx},safe=True)`  

并引发错误:

DuplicateKeyError: E11000 duplicate key error index: data_transfer.nova_mon_test.log.small_20120517202918765432.$notification_1  dup key: { : null } 

为什么?

推荐答案

您的收藏集中可能已经有一个文档,其中包含notification: NULL或未设置通知字段的文档.如果未设置字段,则将其视为null.因为唯一索引每个字段只允许一个值,所以不能有两个没有设置字段的文档.您也可以在创建索引时通过使用sparse选项来解决此问题.这样的事情应该起作用(在notification上已经存在的索引删除之后:

You probably already have a document in your collection which either has notification: NULL or a document that doesn't have the notification field set. If a field is not set, then it's regarded as null. Because a unique index only allows one value per field, you can not have two documents that don't have a field set. You can get around this by also using the sparse option while creating an index. Something like this should work (after dropping the already existing index on notification:

self.db_database[co_name].ensure_index(('notification'),unique=True,sparse=True)

另请参见:稀疏索引和mongo中的空值

这篇关于为什么DuplicateKeyError:E11000重复键错误索引:test.test.$ notification_1 dup键:{:null}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆