2017-01-28 19 views
1
for hashtag in hashtags: 
    existing_hashtag = hashtags_collection.find({"string": hashtag}).limit(1) 
    if existing_hashtag: 
     hashtags_collection.update({"string": hashtag}, 
            {"$inc": {"popularity": 1}})              
    else: 
     new_hashtag = {"string": hashtag, 
         "popularity": 1} 
     hashtags_collection.insert_one(new_hashtag) 

find_one将返回实际的对象,但我听说它效率不高。 find + limit只返回一个游标对象,即使它找不到匹配。那么我怎样才能在MongoDB中实现find + limit?用find()。limit()函数检查mongodb中的文档的正确方法是什么?

回答

0

首先,不要针对您的可迭代的这里的“hashtags”中的每个元素发出查询,而应该使用$in查询运算符。也就是说,您可以使用count方法来检查集合“string”的值中是否有任何文档是您的数组。

collection.count({"string": {"$in": hashtags}}) 

末和并非最不重要的,你不要在这里需要if/else声明,干脆让MongoDB的为你做这项工作可以通过批量操作和upsert选项。

总之,你的代码应该是这样的。

from pymongo import UpdateOne 


bulk_operations = [UpdateOne({'string': value}, {'$inc': {'popularity': 1 }}, upsert=True) 
        for value in hashtags] 
hashtags_collection.bulk_write(bulk_operations) 
相关问题