mongo helper
import datetime
import pymongo
import click
# 数据库基本信息
db_configs = {
'type': 'mongo',
'host': '127.0.0.1',
'port': '27017',
"user": "",
"password": "",
'db_name': 'spider'
}
class Mongo():
def __init__(self):
self.db_name = db_configs.get("db_name")
self.host = db_configs.get("host")
self.port = db_configs.get("port")
self.client = pymongo.MongoClient(f'mongodb://{self.host}:{self.port}', connect=False, maxPoolSize=10)
self.username = db_configs.get("user")
self.password = db_configs.get("passwd")
if self.username and self.password:
self.db = self.client[self.db_name].authenticate(self.username, self.password)
self.db = self.client[self.db_name]
def reset_status(self, col="dianping_seed_data"):
item = dict()
item["status"] = 0
item["update_time"] = datetime.datetime.now()
self.db[col].update_many({'$or': [{'status': 1}, {'status': 3}]}, {'$set': item})
def reset_all_status(self, col="dianping_seed_data"):
item = dict()
item["status"] = 0
item["count"] = 0
item["update_time"] = datetime.datetime.now()
self.db[col].update_many({}, {'$set': item})
def add_index(self, col="dianping_seed_data"):
# status_code 0:初始,1:开始下载,2下载完了
self.db[col].create_index([('status', pymongo.ASCENDING)], unique=True)
def get_index(self, col="dianping_seed_data"):
index_list = self.db[col].list_indexes()
for index in index_list:
print(index)
# 找出重复的放入result表中
def find_duplicate(self, col="dianping_seed_data"):
"""
{'$out': 'result'}:聚合之后将结果写到新的集合result表里。
:param col:
:return:
"""
group = {'$group': {
'_id': {'url': "$url"}, # 以url分组
'_id_list': {'$addToSet': "$_id"}, # _id字段添加到返回结果里面去
'count': {'$sum': 1} # 结果计数加一
}}
# match将上面传过来的结果做进一步处理
match = {"$match": {"count": {"$gt": 1}}}
# 聚合之后的结果输出到表_duplicate_result
out = {'$out': f'{col.split("_")[0]}_duplicate_result'}
try:
result = self.db[col].aggregate([
group, match, out
], allowDiskUse=True)
print("聚合成功")
except Exception as e:
print("聚合失败", e.args)
return result
def delete_dup(self, col="dianping_seed_data"):
dup = f'{col.split("_")[0]}_duplicate_result'
delete_data = self.db[dup].find()
try:
for d in delete_data:
# 保留一条
unique_id_list = d.get("_id_list")[1:]
for did in unique_id_list:
self.db[col].delete_one({'_id': did})
print("准备删除表")
self.db[dup].drop()
print("删除表成功")
except Exception as e:
print("删除的时候出现问题", e.args)
@click.command()
@click.option('--s', type=str, help="状态:all表示全部重置为0,two:表示重置状态为1、3的重置为0")
@click.option('--i', type=str, help="a:增加索引 g:获取索引")
@click.option('--d', type=str, help="d:删除 f:查询并生成聚合之后的结果")
def run(s, i, d):
m = Mongo()
if s:
print("获取参数为:", s)
if s == "all":
print("所有数据状态重置为0:", s)
m.reset_all_status()
elif s == "two":
m.reset_status()
print("部分数据状态重置为0:", s)
if i:
if i == "a":
m.add_index()
elif i == "g":
m.get_index()
if d:
if d == "d":
m.delete_dup()
elif d == "f":
m.find_duplicate()
if __name__ == '__main__':
run()
mongo helper的更多相关文章
- .net 操作MongoDB 基础
1. 下载驱动,最好使用 NuGet 下载,直接搜索MongoDB: 2. 引用相关驱动 3. 部分测试代码,主要是针对MongoDB的GridFS 文件存储来用 using Mongo.Model; ...
- MongoDB - The mongo Shell, Data Types in the mongo Shell
MongoDB BSON provides support for additional data types than JSON. Drivers provide native support fo ...
- MongoDB - The mongo Shell, Write Scripts for the mongo Shell
You can write scripts for the mongo shell in JavaScript that manipulate data in MongoDB or perform a ...
- MongoDB - Introduction of the mongo Shell
Introduction The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mong ...
- 有用的 Mongo命令行 db.currentOp() db.collection.find().explain() - 摘自网络
在Heyzap 和 Bugsnag 我已经使用MongoDB超过一年了,我发现它是一个非常强大的数据库.和其他的数据库一样,它有一些缺陷,但是这里有一些东西我希望有人可以早一点告诉我的. 即使建立索引 ...
- mongo源码学习(四)invariant
前言 在看MongoDB源码的时候,经常会看到这个玩意儿:invariant. invariant的字面意思是:不变式. 在emacs上跳转到函数定义要安装一个插件,ggtags,费了老大劲儿.这都可 ...
- MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell
The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...
- 14.Iterate a Cursor in the mongo Shell-官方文档摘录
1 迭代游标 } ); while (myCursor.hasNext()) { print(tojson(myCursor.next())); } } ); myCursor.forEach(pri ...
- 4.Data Types in the mongo Shell-官方文档摘录
总结: 1.MongoDB 的BSON格式支持额外的数据类型 2 Date 对象内部存储64位字节存整数,存储使用NumberLong()这个类来存,使用NumberInt()存32位整数,128位十 ...
随机推荐
- Vue – 基础学习(1):对生命周期和钩子函的理解
一.简介 先贴一下官网对生命周期/钩子函数的说明(先贴为敬):所有的生命周期钩子自动绑定 this 上下文到实例中,因此你可以访问数据,对属性和方法进行运算.这意味着你不能使用箭头函数来定义一个生命周 ...
- HTML 注释 和 实体字符
一.注释 在HTML中还有一种特殊的标签——注释标签.如果需要在HTML文档中添加一些便于阅读和理解但又不需要显示在页面中的注释文字,就需要使用注释标签. 注释内容不会显示在浏览器窗口中,但是作为HT ...
- 【译】Matplotlib:plotting
前言 本教程源于Scipy Lecture Notes,URL:http://www.scipy-lectures.org/ 本教程若有翻译不当或概念不明之处,请大家留言,博主及时更正,以便后来的用户 ...
- FreeRTOS 任务通知模拟计数型信号量
举例 //释放计数型信号量任务函数 void SemapGive_task(void *pvParameters) { u8 key; while(1) { key = KEY_Scan(0); // ...
- 搜索和浏览离线 Wikipedia 维基百科(中/英)数据工具
为什么使用离线维基百科?一是因为最近英文维基百科被封,无法访问:二是不受网络限制,使用方便,缺点是不能及时更新,可能会有不影响阅读的乱码. 目前,主要有两种工具用来搜索和浏览离线维基百科数据:Kiwi ...
- springboot设置访问端口和项目路径
找到,application.properties, 添加如下配置即可 server.port=8088server.servlet.context-path=/
- 【漏洞复现】PHPStudy后门
0x01 概述 Phpstudy软件是国内一款免费的PHP调试环境程序集成包,通过集成Apache.PHP.MySQL.phpMyAdmin.ZendOptimizer多款软件一次性安装,无需配置即可 ...
- 技术分享 | mysql 表数据校验
1. checksum table. checksum table 会对表一行一行进行计算,直到计算出最终的 checksum 结果.比如对表 n4 进行校验(记录数 157W,大小为 4G) [yt ...
- git命令中的--是什么意思?
转载自git命令中的--是什么意思? git命令中的--是什么意思? 看到个命令 git checkout -- files 不知道--代表什么.查了一下,--是linux的东西,用来标志命令项的结束 ...
- 图论篇2——最小生成树算法(kurskal算法&prim算法)
基本概念 树(Tree) 如果一个无向连通图中不存在回路,则这种图称为树. 生成树 (Spanning Tree) 无向连通图G的一个子图如果是一颗包含G的所有顶点的树,则该子图称为G的生成树. 生成 ...