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 will return actual object but I heard that it is not efficient. find + limit only returns a cursor object even if it doesn't find a match. So how can I implement find + limit in mongodb?
First of all, don't issue a query for each element in your iterable here "hashtags" instead, you should use the $in
query operator.
That being said, you can use the count
method to check whether or not any document in your collection "string"'s value is your array.
collection.count({"string": {"$in": hashtags}})
Last and not least, you don't need the if/else
statement here, simply let MongoDB do the job for you by using bulk operation and the upsert
option.
In conclusion you code should look like this.
from pymongo import UpdateOne
bulk_operations = [UpdateOne({'string': value}, {'$inc': {'popularity': 1 }}, upsert=True)
for value in hashtags]
hashtags_collection.bulk_write(bulk_operations)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments