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 拉卡拉java面试笔试题 (含面试题解析)

      本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.拉卡拉等公司offer,岗位是Java后端开发,因为发展原因最终选择去了拉卡拉,入职一年时间了,也成为了面试官 ...

  2. Django 连接 MySQL 数据库及常见报错解决

    目录 Django 连接 MySQL数据库及常见报错解决 终端或者数据库管理工具连接 MySQL ,并新建项目所需数据库 安装访问 MySQL 的 Python 模块 Django 相关配置 可能会遇 ...

  3. Java 之 Scanner 类

    一.Scanner 类 Scanner 是一个可以解析基本类型和字符串的简单文本扫描器. Demo: Scanner sc = new Scanner(System.in); int i = sc.n ...

  4. Android 中自定义仪表盘

    如图: 自定义属性 values文件下添加 attrs.xml文件 <?xml version="1.0" encoding="utf-8"?> & ...

  5. Android源码分析(三)-----系统框架设计思想

    一 : 术在内而道在外 Android系统的精髓在源码之外,而不在源码之内,代码只是一种实现人类思想的工具,仅此而已...... 近来发现很多关于Android文章都是以源码的方向入手分析Androi ...

  6. Kafka消费者组静态成员(static consumer member)

    Kafka 2.3发布后官网的Consumer参数中增加了一个新的参数:group.instance.id.下面是这个参数的解释: A unique identifier of the consume ...

  7. Vim 中进行文件目录操作

    Vim 中进行文件目录操作 当前文件名 我们知道Vim有48个寄存器,其中%只读寄存器中保存着当前文件路径. 例如在/home/harttle/下打开src/main.cpp,我们打印%的值: :ec ...

  8. Mac安装vscode IDE 撸nodejs代码

    1. vscode官网地址:https://code.visualstudio.com   找到mac对应的下载地址,下载后的文件是 zip压缩包,解压后将文件拖到Application目录下即可. ...

  9. 标准库中的装饰器 lru_cache和全新的 singledispatch

    Python 内置了三个用于装饰方法的函数:property.classmethod 和 staticmethod. 另一个常见的装饰器是 functools.wraps,它的作用是协助构建行为 良好 ...

  10. Httpd服务入门知识-Httpd服务常见配置案例之实现用户家目录的http共享

    Httpd服务入门知识-Httpd服务常见配置案例之实现用户家目录的http共享 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.实现用户家目录的http共享前提 在配置家目录共 ...