首页 > 其他分享 >使用pymongo批量清空表数据

使用pymongo批量清空表数据

时间:2023-05-23 09:33:57浏览次数:35  
标签:index name 批量 app ids collection key 清空 pymongo

背景

性能测试环境,有些入侵的表数据特别多(可能超过1000W),如果使用SQL删除会很慢。但是如果直接把表drop表,索引会丢失。可以写一个脚本,批量清空mongo表数据。

实现思路

说明:以下 xx 为对应的表名

1、备份索引

db.xx.getIndexes();

2、删除表

db.xx.drop();

3、创建表

db.createCollection("xx");
4、使用上面备份的索引重建索引
db.runCommand(
   {
     createIndexes: "app_ids_detection",
     indexes: [
        {
            "v" : 2,
            "key" : {
                "uniqueKey" : 1
            },
            "name" : "idx_unique_key_1",
            "background" : true
        },
        {
            "v" : 2,
            "unique" : true,
            "key" : {
                "detectionId" : 1
            },
            "name" : "uniq_detection_id_1",
            "background" : true
        }
    ]
   }
 )

特别说明:创建表时,默认会有主键索引_id,所以第4步重建索引时需要排除掉主键索引。

 

脚本

新建一个 python 脚本:

#!/usr/bin/python3
#_*_encoding:utf-8_*_
 
"""
    清除表数据
"""
 
import pymongo
 
mongoclient = pymongo.MongoClient("mongodb://root:[email protected]:57019/?authSource=admin&authMechanism=SCRAM-SHA-256&readPreference=primary&directConnection=true&ssl=false")
db_name = "tenant_b3afdca83bc00b013eda"
collection_names = [
    "app_ids_detection",
    "app_ids_detection_temp",
    "app_ids_element",
    "app_ids_activity",
    "app_ids_incident",
    "app_ids_incident_element",
    "app_ids_element_path",
    "app_ids_incident_statistics",
    "app_ids_incident_statistics_history",
    "app_ids_disposal_record",
    "app_ids_scan_result",
    "app_ids_detection_whiterule",
    "app_ids_white_rule",
    "app_ids_whiterule_hit_detection",
    "app_ids_login_event",
    "app_ids_notify_aggregate_event",
    "app_ids_script_dynamic_whitelist",
    "app_ids_success_login_event",
    "app_ids_memwebshell_enable_agent",
    "app_ids_memwebshell_inject",
    "app_ids_ioa",
    "app_ids_ioa_history",
    "app_ids_ioa_sync_send_status",
    "app_ids_ioa_sync_agent_history",
    "app_ids_yara_lib_version",
    "app_ids_element_operation_history"
]
db = mongoclient[db_name]
 
# 查询表的所有索引(不包含主键ID)
def get_collection_indexes(collection_name):
    collection = db[collection_name]
    index_info_dict = collection.index_information()
 
    index_list = []
    for index_key in index_info_dict:
        if index_key != "_id_":
            index_value = index_info_dict[index_key]
 
            # 增加索引名称
            index_value["name"] = index_key
 
            # 修改key结构:list->obj
            key_obj = {}
            key_list = index_value["key"]
            for field, field_sort in key_list:
                key_obj[field] = field_sort
            index_value["key"] = key_obj
 
            index_list.append(index_value)
 
    return index_list
 
# 重建表结构(清空表数据)
def re_create_collection(collection_name):
    collection = db[collection_name]
    collection.drop()
    db.create_collection(collection_name)
 
# 重建索引
def create_index(collection_name, collection_indexes):
    db.command({
        "createIndexes": collection_name,
        "indexes": collection_indexes
    })
 
if __name__ == "__main__":
    for collection_name in collection_names:
        collection_indexes = get_collection_indexes(collection_name)
        if len(collection_indexes) > 0:
            re_create_collection(collection_name)
            create_index(collection_name, collection_indexes)
            print(f"{collection_name} clear data success~")
        else:
            print(f"{collection_name} indexes is empty!")
清除表数据脚本

说明:

  • 执行脚本前,环境信息:根据具体环境,替换mongo账户名/密码,以及ip地址
    • python3环境
    • 安装pymongo模块:sudo pip3 install pymongo
  • 根据具体环境,替换mongo账户名/密码,以及ip地址
  • 根据具体需求,替换需要清除的库和表名称
 

标签:index,name,批量,app,ids,collection,key,清空,pymongo
From: https://www.cnblogs.com/xuwenjin/p/17422334.html

相关文章

  • 批量执行mysql文件
    mysqldumpMysql数据备份恢复目录mysqldumpMysql数据备份恢复一、需求二、Java实现Mysql备份与恢复pom.xmlmainMysqlBackupsMysqlReductionConfPropresources执行一、需求实现Mysql数据库备份与恢复/***mysqldump命令*备份库*备份所有数据库:mysqldump-h主机IP......
  • 通用 Mapper 的批量插入实现
    具体的SQL模板实现如下所示:importorg.apache.ibatis.mapping.MappedStatement;importtk.mybatis.mapper.MapperException;importtk.mybatis.mapper.entity.EntityColumn;importtk.mybatis.mapper.mapperhelper.EntityHelper;importtk.mybatis.mapper.mapperhelper.Map......
  • Word批量修改图片环绕方式与尺寸大小
    前提:一份Word文档里面有100张图片,有大有小,需要将100张图片更改为统一大小,宽度与高度均为5厘米,同时环绕方式也需要改成四周型。默认Word图片的默认环绕方式为嵌入型,需要统一更改为四周型,然后才能批量更改大小,而批量更改大小方式需要使用VBA代码。第一步:打开 Word文档,并按下Alt+......
  • Common Lisp 批量处理生成HTML网页
    在组织磁盘文件的时候,想到HTMLweb的超级链接对知识有帮助,利用书籍《 PracticalCommonLisp》中的可移植的文件系统库。实现了遍历e盘的图像文件夹,生成多个网页文件,并收集所有的html后缀文件生成超链接。知识点:HTML编辑,文件系统遍历,CommonLisp宏代码如下: (defparamete......
  • 在Centos7上安装PXE装机环境来批量安装操作系统
    步骤1:安装必要的软件包首先,需要确保系统已安装dhcp、tftp-server和httpd等软件包。可以使用以下命令进行安装:yuminstall-ydhcptftp-serverhttpdsyslinux-tftpbootxinetd步骤2:配置DHCP服务器接下来,需要配置DHCP服务器以向客户端分配IP地址。在/etc/dhcp/d......
  • python批量处理excel数据、批量透视、合并透视表
    ###t+21importpandasaspdimportos#半自动———#——<创建好格式文件夹#——<数据下载至文件夹#——<修改date#——<运行##直播时间date='4.21'#读取存放文件路径read_path='E:/test/t+21/'+date+'/1原始数据'path_list=os.listdir(read_path)pathdir=''writ......
  • Chrome浏览器好用的插件(批量保存所有选项卡网址、批量打开粘贴板网址插件)
    转自:https://www.cnblogs.com/nmap/p/6557883.html 1、Chrome批量保存所有选项卡网址+批量打开复制网址小插件批量保存所有选项卡网址插件:CopyAllUrls经常搜索一些东西,下班时无法处理完所有网页内容,比如做笔记什么的,又不舍得关闭网页。每个页面关闭前复制链接保存太麻烦......
  • [SEO知识讲解] 揭秘大批量做“多个关键词快排技巧”
    本文转载自:[SEO知识讲解]揭秘大批量做“多个关键词快排技巧”更多内容请访问钻芒博客:https://www.zuanmang.net做SEO优化的人都知道,同一个关键词如果你排在竞争对手的前面,那么你的机会就更多。网站前期的策划也好,用户体验也好,都需要通过关键词,才能把真正的客户带到网站,变成实实......
  • [SEO知识讲解] 关键词如何批量优化?
    本文转载自:[SEO知识讲解]关键词如何批量优化?更多内容请访问钻芒博客:https://www.zuanmang.net最近有朋友发来邮件,问我长尾词太多了,一个一个优化不现实,怎么样才能大量的做长尾词。这个问题很有意义,可能一个长尾,10个长尾你会觉得简单,而一万个长尾十万个长尾,肯定会有一定的差别。......
  • 网站如何才能不让采集工具批量采集
    因为会点编程的缘故,所以浏览任何网站的时候都会学着去评估这个网站的价值、网站数据的实用性以及这个网站采集的难易度。看得多了便列两条那种很容易采集的要点,希望以后做网站的人能够知道点如何保护自己的网站网站内容数据吧。1.每个页面或者图片以序号的方式储存。2.图片未加......