python – 为什么DuplicateKeyError:E11000重复键错误索引:test.test.$notification_1 dup key:{: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)`  

在插入之前我创建一条记录如下:

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)`  

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

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 } 

为什么?

解决方法:

您的集合中可能已有一个文档,该文档具有通知:NULL或未设置通知字段的文档.如果未设置字段,则将其视为空.由于唯一索引仅允许每个字段使用一个值,因此您不能拥有两个没有字段集的文档.您可以在创建索引时使用稀疏选项来解决此问题.这样的东西应该工作(在通知上删除已经存在的索引之后:

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

另见:sparse indexes and null values in mongo

上一篇:python – PyMongo和toArray()方法


下一篇:python – PyMongo游标迭代