2013-11-27 40 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工作,但我测试了为工作。