python – Mongoengine – 如何执行“保存新项目或增量计数器” *** 作?

python – Mongoengine – 如何执行“保存新项目或增量计数器” *** 作?,第1张

概述我在一个网络抓取项目中使用MongoEngine.我想跟踪我在所有抓取的网页上遇到的所有图像. 为此,我存储图像src URL和图像遇到的次数. MongoEngine模型定义如下: class ImagesUrl(Document): """ Model representing images encountered during web-scraping. When an i 我在一个网络抓取项目中使用MongoEngine.我想跟踪我在所有抓取的网页上遇到的所有图像.

为此,我存储图像src URL和图像遇到的次数.

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)

有没有更好的方法呢?

非常感谢您的宝贵时间.

解决方法 你应该能够做一个 upsert,例如:
ImagesUrl.objects(src=self.src).update_one(                                  upsert=True,inc__counter=1,set__src=self.src)
总结

以上是内存溢出为你收集整理的python – Mongoengine – 如何执行“保存新项目或增量计数器” *** 作?全部内容,希望文章能够帮你解决python – Mongoengine – 如何执行“保存新项目或增量计数器” *** 作?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1207308.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存