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. Mysql之视图和事务(五)

    一:视图 1.问题 对于复杂的查询,往往是有多个数据表进行关联查询而得到,如果数据库因为需求等原因发生了改变,为了保证查询出来的数据与之前相同,则需要在多个地方进行修改,维护起来非常麻烦 解决办法:定 ...

  2. pandas-16 pd.merge()的用法

    pandas-16 pd.merge()的用法 使用过sql语言的话,一定对join,left join, right join等非常熟悉,在pandas中,merge的作用也非常类似. 如:pd.m ...

  3. 【开发笔记】- 修改tomcat默认的编码方式

    tomcat8以后默认编码格式是utf-8:7之前的都是iso8859-1 如果默认情况下,tomcat使用的的编码方式:iso8859-1 修改tomcat下的conf/server.xml文件 找 ...

  4. Object中defineProperty数据描述

    Object.defineProperty是对对象中的属性进行数据描述的 使用语法: Object.defineProperty(obj,prop,descriptor) 使用示例: var data ...

  5. js学习之面向对象

    一.创建对象的方法 1. {} 字面量创建 var person ={ name: "lisi", age: , say: function(){ alert(this.name) ...

  6. css3做ipone当时的滑动解锁闪亮条

    现在一般的登录 注册 什么  的页面,都是会做个滑动验证.一般都是像IPONE早期那个 滑动开屏的效果 ,这个效果现在可以用CSS3来实现. 主要用到几个属性 background 背景使用渐变属性, ...

  7. App的开发过程(转载)

    来源:https://www.cnblogs.com/sanwenyu/p/7234616.html 不同的项目管理模式或许会有完全不同的流程步骤.但是专业性几乎是保证产品质量的唯一准则. App的开 ...

  8. Centos 7 kubernetes集群搭建

    一.环境准备 Kubernetes支持在物理服务器或虚拟机中运行,本次使用虚拟机准备测试环境,硬件配置信息如表所示: IP地址 节点角色 CPU Memory Hostname 磁盘 192.168. ...

  9. 小型SSM项目出现Failed to load ApplicationContext错误的解决方法(个人向)

    使用单元测试的时候,出现了Failed to load ApplicationContext错误,在添加了一个新的Mapper.xml文件才出现的,在保证其他配置文件没有出错的情况下,检查mapper ...

  10. 利用tcpdump抓取网络包

    1.下载并安装tcpdump 下载地址:tcpdump 安装tcpdump,连接adb adb push tcpdump /data/local/tcpdump adb shell chmod 675 ...