2012-06-02 43 views
3

我創建唯一索引是這樣的:

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 } 

爲什麼?

回答

16

您的收藏中可能已經有一個文檔,其中包含notification: NULL或者沒有設置通知字段的文檔。如果一個字段沒有設置,那麼它被認爲是空的。由於唯一索引只允許每個字段有一個值,因此不能有兩個沒有設置字段的文檔。您可以在創建索引時通過使用sparse選項來解決此問題。像這樣的東西應該工作(上notification丟棄現有的索引之後:

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

參見:sparse indexes and null values in mongo

+0

我的作品時,我添加稀疏=真,非常感謝你 – user1420895

+3

@ user1420895這是一個好主意「接受」的答案,因爲它解決了您的問題。請參閱http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

+0

@derick是這就是答案,謝謝! –

相關問題