为什么重复密钥错误:E11000重复密钥错误索引:test.test。$notification_1 dup key:{:null}

2024-05-23 17:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建的唯一索引如下:

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 } 

为什么?


Tags: nameselfsrctruedbsizeindextime
1条回答
网友
1楼 · 发布于 2024-05-23 17:09:58

您的集合中可能已经有一个具有notification: NULL的文档,或者没有设置通知字段的文档。如果未设置字段,则将其视为空。因为唯一索引只允许每个字段有一个值,所以不能有两个没有字段集的文档。创建索引时还可以使用sparse选项来解决这个问题。类似的操作应该可以(在删除notification上已经存在的索引之后:

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

另请参见:sparse indexes and null values in mongo

相关问题 更多 >