【问题标题】:if data is available don't save to mongo-python如果数据可用,请不要保存到 mongo-python
【发布时间】:2020-10-22 08:23:21
【问题描述】:

我每 10 分钟使用 python 将数据从新闻站点拉到 mongodb。有时会记录相同的数据。因为无法控制相同的数据。如果有相同的传入数据,请不要保存到 mongodb。

import feedparser
import datetime
import threading
import pymongo
from pymongo import MongoClient


client = pymongo.MongoClient("mongodb+srv://xxx:xxx@cluster0-ogqg8.mongodb.net/rss_feed?retryWrites=true&w=majority")
db = client["rss_feed"]
collection=db["rss_collection"]


def mynet():
    NewsFeedMynet = feedparser.parse("http://www.mynet.com/haber/rss/sondakika")
    entry = NewsFeedMynet.entries[1]

post_mynet={"baslik":entry.title,"kisa_bilgi":entry.summary,"link":entry.link,"zaman":entry.published,"saglayici":"Mynet"}
collection.insert_one(post_mynet)

【问题讨论】:

  • 程序有时会循环记录相同的数据(有时新闻网站不刷新新闻)。请在此处检查有关相同数据的代码

标签: python mongodb aggregation-framework rss insert-update


【解决方案1】:

有两种方法可以解决这个问题:

一个是 upsert,如果记录在那里并且具有相同的标题,则更新正文。如果记录不存在,则插入。

post_mynet = {"baslik":entry.title,"kisa_bilgi":entry.summary,"link":entry.link,"zaman":entry.published,"saglayici":"Mynet"}
# first parameter is "what to match", aka, query
# second parameter is the record
# third is the flag to upsert
collection.update_one({"baslik": entry.title}, post_mynet, upsert=True)

另一种是检查记录是否存在,如果存在则不更新:

post_mynet = {"baslik":entry.title,"kisa_bilgi":entry.summary,"link":entry.link,"zaman":entry.published,"saglayici":"Mynet"}
if not collection.find_one({"baslik": entry.title}):
    collection.insert_one(post_mynet)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多