Pycharm访问MongoDB数据库
MongoDB的基础操作
1. 创建连接
#导入pymongo中的用于操作数据库的客户端
from pymongo import MongoClient
#创建客户端对象,连接MongoDB服务器
client = MongoClient('mongodb://admin:admin123456@localhost:27017')
2. 数据的增删改查
2.1 数据的写入
from mongo_db import client
client.school.teacher.insert_one({"name":"Hela"})
client.school.teacher.insert_many([
{"name":"Zoya"},
{"name":"Adela"},
{"name":"Hecate"},
])
2.2 数据的查询
from mongo_db import client
try:
#查询所有记录
teachers = client.school.teacher.find({})
for one in teachers:
print(one["_id"], one["name"], one["role"])
print("----------")
#有条件查询
teacher = client.school.teacher.find_one({"name":"Hecate"})
print(teacher["_id"], teacher["name"])
except Exception as e:
print(e)
2.3 数据的修改
from mongo_db import client
try:
#全表修改
client.school.teacher.update_many({},{"$set":{"role":["班主任"]}})
#有条件修改
client.school.teacher.update_one({"name":"Zoya"}, {"$set":{"sex":"female"}})
client.school.teacher.update_one({"name":"Zoya"}, {"$push":{"role": ["年级主任"]}})
except Exception as e:
print(e)
2.4 数据的删除
from mongo_db import client
try:
#有条件删除
client.school.teacher.delete_one({"name":"Zoya"})
#删除所有
client.school.teacher.delete_many({})
except Exception as e:
print(e)
3. 分页去重与排序
序号 | 函数 | 功能 |
---|---|---|
1 | skip | 用于数据分页查询 |
2 | limit | 用于数据分页查询 |
3 | count | 查询记录总数 |
4 | distinct | 查询不重复的字段值 |
5 | sort | 对记录排序 |
from mongo_db import client
#分页
teachers = client.school.teacher.find({}).skip(0).limit(10)
for one in teachers:
print(one["_id"],one["name"])
#去重
teachers = client.school.teacher.distinct('name')
for one in teachers:
print(one)
#排序,按名字排序,降序
teachers = client.school.teacher.find({}).sort([("name",-1)])
for one in teachers:
print(one["_id"],one["name"])
4. 存PDF文件进MongoDB中
from mongo_db import client
# 处理大格式文件的工具
from gridfs import GridFS
db = client.school
# 操作名字为book的数据集
gfs = GridFS(db,collection="book")
# 获取文件的二进制数据
file = open("D:/workspace/images/Linux就该这么学.pdf","rb")
# 准备文件的描述数据
args = {"type":"PDF","keyword":"linux"}
# 向mongodb数据库中存放数据
# 参数1:文件的二进制;参数2:文件的名字;参数3:文件的相关描述
gfs.put(file,filename="Linux就该这么学.pdf",**args)
file.close()
5. 查询文件基本信息
from mongo_db import client
from gridfs import GridFS
# 用于数学运算的工具,包括随机数等
import math
# 日期时间工具
import datetime
db = client.school
gfs = GridFS(db,collection="book")
book = gfs.find_one({"filename":"XXXXXXX.pdf"})
# 获取文件描述相关信息
print(book.filename)
print(book.type)
print(book.keyword)
print("%dM"%math.ceil(book.length/1024/1024))
print("---------------------")
# 查询文件
books = gfs.find({"type":"PDF"})
for one in books:
# 获取系统时间
uploadDate = one.uploadDate+datetime.timedelta(hours=8)
# 对日期时间进行格式化
uploadDate = uploadDate.strftime('%Y-%m-%d %H:%M:%S')
print(one._id,one.filename,uploadDate)
6. 导出数据库文件
from mongo_db import client
from gridfs import GridFS
# 处理MongoDB生成的id值
from bson.objectid import ObjectId
# 获取文件
# 匹配_id、文件名、文件格式,打印文件是否存在
rs = gfs.exists(ObjectId("6762263b4639c36eb91f064b"))
print(rs)
rs = gfs.exists(**{"filename":"Linux就该这么学.pdf"})
print(rs)
rs = gfs.exists(**{"type":"PDF"})
print(rs)
#根据id值获取文件内容
document = gfs.get(ObjectId("6762263b4639c36eb91f064b"))
#在本地创建文件
file = open("D:/workspace/images/Linux还能这么学.pdf","wb")
# 向新建的文件中输入二进制数据
file.write(document.read())
file.close()
7. 删除数据库文件
from mongo_db import client
from gridfs import GridFS
from bson.objectid import ObjectId
db = client.school
gfs = GridFS(db,collection="book")
gfs.delete(ObjectId("66fa39f78bb8a8fb4d287a98"))