3
votes

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

1 Answers

17
votes

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