如何为 Pymongo 进行数据库更新插入?

发布于 2025-01-18 13:15:55 字数 1098 浏览 2 评论 0原文

我想使用 upsert 与 MongoDB 和 pymongo 添加大约 10 个数据项,但只添加了 1 个项目。 如何添加 10 个案例?

当然,使用 insert 可以获得 10 个案例,但我想使用 upsert 因为我想在更新时添加数据。

谢谢。

url = 'https://watcher.guru/news/category/metaverse'

def db_set(self):
    db_url = 'mongodb://pyton:[email protected]:27017'
    client = pymongo.MongoClient(db_url)
    db = client.blog
    collection = db.crypto

    return collection

def article_parse(self):
    url_lists: list =  self.article()
    collection =  self.db_set()

    for url in url_lists:
        respon = self.response(url)
        soup = self.soup(respon)
        title = soup.find('div', {'id': 'primary'}).find('h1').text
        url = url
        texts = soup.find('div', {'class': 'entry-content'}).text.strip()
        print(texts)
        print('---------------------')

        collection.update_many({}, {'$set':{'title': title, 'url': url, 'text': texts}}, upsert=True)

I want to use upsert with MongoDB and pymongo to add about 10 data items, but only 1 item is added.
How can I add 10 cases?

Of course it is possible to get 10 cases using insert, but I want to use upsert because I want to add the data when it is updated.

Thanks.

url = 'https://watcher.guru/news/category/metaverse'

def db_set(self):
    db_url = 'mongodb://pyton:[email protected]:27017'
    client = pymongo.MongoClient(db_url)
    db = client.blog
    collection = db.crypto

    return collection

def article_parse(self):
    url_lists: list =  self.article()
    collection =  self.db_set()

    for url in url_lists:
        respon = self.response(url)
        soup = self.soup(respon)
        title = soup.find('div', {'id': 'primary'}).find('h1').text
        url = url
        texts = soup.find('div', {'class': 'entry-content'}).text.strip()
        print(texts)
        print('---------------------')

        collection.update_many({}, {'$set':{'title': title, 'url': url, 'text': texts}}, upsert=True)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文