如何检查$ addToSet在mongodb中返回true或false?

问题描述:

如果数据不重复,我想检查文件中的字段(pv_time),然后在pv_time和其他字段中插入数据。在其他字段中允许复制。使用$addToSet我试图做到这一点。

这里是我的Python代码:

for row in results.get('rows'): 
    path = row[0] 
    feedbackId = row[1] 
    pvDate = row[2]+' '+row[3]+':'+row[4] 
    city = row[5] 
    country = row[6] 
    pageviews = int(row[7]) 
    db.customer_feedback_requests_archive.update({'feedback_request_id':ObjectId(feedbackId)},{'$addToSet':{'pv_time.'+path:pvDate},'$push':{'pv_city.'+path:city,'pv_country.'+path:country},'$inc':{'pv_count.'+path:pageviews}}) 

如果我跑这第一次是给了

{ 
     "_id" : ObjectId("558d3900996f95a24aa69ef3"), 
     "feedback_request_id" : ObjectId("5665015a882a5174379d4dbd"), 
     "pv_count" : { 
       "main-rating" : 2 
     }, 
     "pv_city" : { 
       "main-rating" : [ 
         "Bengaluru", 
         "Bengaluru" 
       ] 
     }, 
     "pv_country" : { 
       "main-rating" : [ 
         "India", 
         "India" 
       ] 
     }, 
     "pv_time" : { 
       "main-rating" : [ 
         "20151208 10:00", 
         "20151208 10:01" 
       ] 
     } 
} 

但是,如果我运行此作业两次,然后它给:

{ 
     "_id" : ObjectId("558d3900996f95a24aa69ef3"), 
     "feedback_request_id" : ObjectId("5665015a882a5174379d4dbd"), 
     "pv_count" : { 
       "main-rating" : 4 
     }, 
     "pv_city" : { 
       "main-rating" : [ 
         "Bengaluru", 
         "Bengaluru", 
         "Bengaluru", 
         "Bengaluru" 
       ] 
     }, 
     "pv_country" : { 
       "main-rating" : [ 
         "India", 
         "India", 
         "India", 
         "India" 
       ] 
     }, 
     "pv_time" : { 
       "main-rating" : [ 
         "20151208 10:00", 
         "20151208 10:01" 
       ] 
     } 
} 

我想要pv_citypv_country中的重复值只有在pv_time是不同的,第二次我期待如果pv_time没有更新,那么它不应该更新pv_citypv_country

+0

是否有特定的原因,你为什么这样构建你的文件? – tonyl7126

+0

因此,只有在当前pv_time与集合中的所有值不同的情况下,才需要将值添加到pv_city和pv_country中? – blackmamba

+0

@ tonyl7126是的,还有一些原因 – imSonuGupta

它相当简单,你只需要扩展你的查询一点点。

db.customer_feedback_requests_archive.update(
    {'feedback_request_id':ObjectId(fee‌​dbackId),'pv_time.'+path:{'$ne':pvDate}}, 
    {'$addToSet':{'pv_time.'+path:pvDate},'$‌​push':{'pv_city.'+path:city,'pv_country.'+path:country},'$inc':{'pv_count.'+path:‌​pageviews}} 
) 

额外查询参数的作用是,它会搜索数组是否已经有日期。如果它不存在,更新将会触发,这将解决您的问题。