-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb.py
49 lines (40 loc) · 1.56 KB
/
mongodb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from bson import ObjectId
import pymongo
import urllib.parse
__DATABASE_NAME__ = "NewsDB"
class MongoDb:
__mongo_client__ = None
__collection__ = None
# 类构造函数 #
def __init__(self, addr, port, user=None, pwd=None, conn_uri=None):
if conn_uri is not None:
self.__mongo_client__ = pymongo.MongoClient(conn_uri)
return
user = urllib.parse.quote_plus(user)
pwd = urllib.parse.quote_plus(pwd)
# 创建mongodb连接
if user is not None and pwd is not None:
self.__mongo_client__ = pymongo.MongoClient("mongodb://{0}:{1}@{2}:{3}/".format(user, pwd, addr, port))
else:
self.__mongo_client__ = pymongo.MongoClient("mongodb://{0}:{1}/".format(addr, port))
# 类析构函数 #
def __del__(self):
self.__mongo_client__.close()
# 设置使用的集合名称
def set_collection(self, collection):
self.__collection__ = self.__mongo_client__[__DATABASE_NAME__][collection]
# 将解析到的新闻存入数据库
def put_newslist(self, news_list):
for news in news_list:
self.put_news(news)
def put_news(self, news):
self.set_collection(news["type"])
query = self.__collection__.find_one({"url": news['url']})
if query is None:
self.__collection__.insert_one(news)
def get_news_count(self):
count = 0
db = self.__mongo_client__[__DATABASE_NAME__]
for coll in db.collection_names():
count += db[coll].estimated_document_count()
return count