python删除mongo表

PyMongo

Python 要连接 MongoDB 需要 MongoDB 驱动,这里我们使用 PyMongo 驱动来连接。

pip 安装

pip 是一个通用的 Python 包管理工具,提供了对 Python 包的查找、下载、安装、卸载的功能。

安装 pymongo:

1
$ python3 -m pip3 install pymongo

也可以指定安装的版本:

1
$ python3 -m pip3 install pymongo==3.5.1

更新 pymongo 命令:

1
$ python3 -m pip3 install --upgrade pymongo

easy_install 安装

旧版的 Python 可以使用 easy_install 来安装,easy_install 也是 Python 包管理工具。

1
$ python -m easy_install pymongo

更新 pymongo 命令:

1
$ python -m easy_install -U pymongo

创建数据库

创建数据库需要使用 MongoClient 对象,并且指定连接的 URL 地址和要创建的数据库名。

如下实例中,我们创建的数据库 aa :

1
2
3
4
5
6
#!/usr/bin/python3

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["aa"]

删除表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python

#-*- coding: utf-8 -*-

from pymongo import MongoClient
from datetime import datetime

def delete(year,month,day):
try:
client = MongoClient('mongodb://192.168.50.223:27017,192.168.50.224:27017,192.168.50.225:27017')
db_auth = client.admin
db_auth.authenticate("root", "passwd")
db = client.gag_bill
old_count = db.billInfo.count()
print ("old_count = %d" % (old_count))
db.billInfo.remove({"cTimeStamp":{"$lte":datetime(year,month,day,0,0,0,000)}})
new_count = db.billInfo.count()
client.close()
print ("del_data = %d" %(old_count-new_count))
print ("new_count = %d" % (new_count))
except Exception as e:
print (e)

if __name__ == '__main__':
starttime = datetime.now()
print ("start_time = %s" % (starttime))
year = starttime.year
month = starttime.month
day = starttime.day-4
delete(year,month,day)
endtime = datetime.now()
print ("end_time = %s" % (endtime))
runtime = (endtime - starttime).seconds
print ("run_time = %d seconds" % (runtime))
Donate