2013-11-27 41 views
0

是否可以在記錄中使用ensureindex而不是整個集合。Mongodb - ensureindex備案

例如:我的數據庫結構

{ "_id" : "com.android.hello", 
    "rating" : [  
     [ { "user" : "BBFE7F461E10BEE10A92784EFDB",  "value" : "4" } ], 
     [ { "user" : "BBFE7F461E10BEE10A92784EFDB",  "value" : "4" } ] 
    ] 
} 

這是一個評級系統,我不希望用戶在同一個應用程序(com.android.hello)率多次。如果我在user字段上使用ensureindex,那麼用戶只能對一個應用程序投票。當我嘗試投票完全不同的應用程序(com.android.hi)時,它說重複的密鑰。

回答

0

不,你不能這樣做。唯一性僅在每個文檔級別上執行。您將需要重新設計您的模式以使上述工作。例如到:

{ 
    "_id" : "com.android.hello", 
    "rating": { 
     "user" : "BBFE7F461E10BEE10A92784EFDB", 
     "value" : "4" 
    } 
} 

然後就是存儲多...

(我知道你沒有提供完整的文檔雖然)

0
     ensureIndex 

創建索引,這是適用於整個收藏。如果您只需要少量記錄,則可能需要保留兩個集合並在其中一個集合上應用ensureIndex。

0

正如@Derick說,不但是有可能,以確保他們只能投票一次原子:

var res=db.votes.update(
    {_id: 'com.android.hello', 'rating.user': {$nin:['BBFE7F461E10BEE10A92784EFDB']}}, 
    {$push:{rating:{user:'BBFE7F461E10BEE10A92784EFDB',value:4}}}, 
    {upsert:true} 
); 
if(res['upserted']||res['n']>0){ 
    print('voted'); 
}else 
    print('nope'); 

我還是有點擔心,$push不會在upsert工作,但我測試了爲工作。