why DuplicateKeyError: E11000 duplicate key error index: test.test.$notification_1 dup key: { : null }

我怕爱的太早我们不能终老 提交于 2019-12-07 12:48:16

问题


i create unique index like this:

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

and it raise a error :

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

WHY?


回答1:


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)

See also: sparse indexes and null values in mongo



来源:https://stackoverflow.com/questions/10863561/why-duplicatekeyerror-e11000-duplicate-key-error-index-test-test-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!