Mongoengine - 如何执行“保存新项或递增计数器”的操作?
我在一个网页抓取项目中使用MongoEngine。我想记录我在所有抓取到的网页上遇到的所有图片。
为此,我保存了图片的src
网址和这张图片出现的次数。
MongoEngine的模型定义如下:
class ImagesUrl(Document):
""" Model representing images encountered during web-scraping.
When an image is encountered on a web-page during scraping,
we store its url and the number of times it has been
seen (default counter value is 1).
If the image had been seen before, we do not insert a new document
in collection, but merely increment the corresponding counter value.
"""
# The url of the image. There cannot be any duplicate.
src = URLField(required=True, unique=True)
# counter of the total number of occurences of the image during
# the datamining process
counter = IntField(min_value=0, required=True, default=1)
我在寻找一个合适的方法来实现“保存或增加”的过程。
到目前为止,我是这样处理的,但我觉得可能有更好、更简单的方法可以用MongoEngine来实现:
def save_or_increment(self):
""" If it is the first time the image has been encountered, insert
its src in mongo, along with a counter=1 value.
If not, increment its counter value by 1.
"""
# check if item is already stored
# if not, save a new item
if not ImagesUrl.objects(src=self.src):
ImagesUrl(
src=self.src,
counter=self.counter,
).save()
else:
# if item already stored in Mongo, just increment its counter
ImagesUrl.objects(src=self.src).update_one(inc__counter=1)
有没有更好的方法呢?
非常感谢你的时间。
2 个回答
0
在@ross的回答中提到的update_one
方法,会告诉你有多少个文档被修改了(或者更新的完整结果),但它不会返回更新后的文档或者新的计数数字。如果你想要这些信息,你应该使用upsert_one
:
images_url = ImagesUrl.objects(src=self.src).upsert_one(
inc__counter=1,
set__src=self.src)
print images_url.counter
这个方法会在文档不存在时创建一个新的文档,或者如果文档已经存在,就修改它并增加计数数字。
11
你可以直接使用一个叫做 upsert 的操作,举个例子:
ImagesUrl.objects(src=self.src).update_one(
upsert=True,
inc__counter=1,
set__src=self.src)