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的更多相关文章

  1. .net 操作MongoDB 基础

    1. 下载驱动,最好使用 NuGet 下载,直接搜索MongoDB: 2. 引用相关驱动 3. 部分测试代码,主要是针对MongoDB的GridFS 文件存储来用 using Mongo.Model; ...

  2. 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 ...

  3. 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 ...

  4. MongoDB - Introduction of the mongo Shell

    Introduction The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mong ...

  5. 有用的 Mongo命令行 db.currentOp() db.collection.find().explain() - 摘自网络

    在Heyzap 和 Bugsnag 我已经使用MongoDB超过一年了,我发现它是一个非常强大的数据库.和其他的数据库一样,它有一些缺陷,但是这里有一些东西我希望有人可以早一点告诉我的. 即使建立索引 ...

  6. mongo源码学习(四)invariant

    前言 在看MongoDB源码的时候,经常会看到这个玩意儿:invariant. invariant的字面意思是:不变式. 在emacs上跳转到函数定义要安装一个插件,ggtags,费了老大劲儿.这都可 ...

  7. 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 ...

  8. 14.Iterate a Cursor in the mongo Shell-官方文档摘录

    1 迭代游标 } ); while (myCursor.hasNext()) { print(tojson(myCursor.next())); } } ); myCursor.forEach(pri ...

  9. 4.Data Types in the mongo Shell-官方文档摘录

    总结: 1.MongoDB 的BSON格式支持额外的数据类型 2 Date 对象内部存储64位字节存整数,存储使用NumberLong()这个类来存,使用NumberInt()存32位整数,128位十 ...

随机推荐

  1. 2019-08-01 Ajax实现从数据库读取表

    php代码 <?php //用pdo连接数据库 $dsn = 'mysql:host=127.0.0.1;port=3306;charset=utf8;dbname=news'; //实例化PD ...

  2. Vue第一天

    什么是 Vue.js? Vue.js是前端的主流框架之一,与 Angular.js.React.js一起,并称为前端三大主流框架 Vue.js是一套构建用户界面的框架,只关注视图层,它不仅易上手,还便 ...

  3. JavaScript 之 页面加载事件

    一.onload 加载事件 onload 是 window 对象的一个事件,也可以省略 window 直接使用. 常用方式: <head><script> windown.on ...

  4. [转]C++类成员修饰const和mutable

    const:常量,不变的 mutable:易变的 从意思上理解,可见const和mutable是一对反义词,它们都是C++的关键字. const成员函数不能修改调用它的对象.类的成员函数可以被声明为c ...

  5. Dalvik虚拟机结构——1

    Dalvik核心内容:libdvm.so  主要有C语言实现,依赖于Linux内核的一部分功能:线程机制,内存管理机制,每一个Android应有都对应一个dalvik实例 Dalvik虚拟机功能:主要 ...

  6. Python实现的贪婪算法

    个州的听众都收听到.为此,你需要决定在哪些广播台播出.在每个广播台播出都需要支出费用,因此你力图在尽可能少的广播台播出 # 1.创建一个列表,其中包含要覆盖的州 states_needed = set ...

  7. golang http 服务器的接口梳理

    golang http 服务器的接口梳理 Golang构建HTTP服务(二)--- Handler,ServeMux与中间件 Hanlde和HandleFunc以及Handler, HandlerFu ...

  8. windows定时器编程

    目前,Windows下的定时器编程主要有三种方式. 1)SetTimer定时器是利用Windows窗口消息WM_TIMER来实现的.使用方法非常简单,SetTimer创建定时器,KillTimer销毁 ...

  9. 关于ping github.com超时的解决办法

    今天在使用git的时候执行将本地分支推送到远程分支的push操作时(同时为远程库创建和本地分支同名的分支),遇到了超时的错误,经过查询全网各位大牛的操作这里给出有效解决方式 进入C:\Windows\ ...

  10. BitMap 图片格式与Base64Image格式互转方法

    BitMap 图片格式与Base64Image格式互转方法 /// <summary> /// 图片转为base64编码的字符串 /// </summary> /// < ...