数据库
首页 > 数据库> > MongoDB(4)- MongoDB与Python的交互

MongoDB(4)- MongoDB与Python的交互

作者:互联网

1.pymongo的安装与使用

1.1.pymongo安装

安装pymongo

pymongodb模块api官方文档:https://pymongo.readthedocs.io/en/stable/tutorial.html

pip install pymongo

1.2.pymongo使用

1.2.1.创建连接

1 from pymongo import MongoClient
2 
3 client=MongoClient(host="localhost",port=27017,)
4 client.admin.authenticate("admin","123456")

报错:运行上述脚本报错

解决报错:

问题分析:上述的写法是针对pymongo老版本的写法,而我们pip安装的时候没有加版本号,因此下载安装的是最新版本的

项目设置选择pymongo最新版本 

换最新包的写法

1 from pymongo import MongoClient
2 
3 client=MongoClient(host="localhost",
4                    port=27017,
5                    username="admin",
6                    password="123456")

1.2.2.数据写入

1 from mongo_db import client
2 
3 client.school.teacher.insert_one({"name":"李璐"})
4 client.school.teacher.insert_many([
5     {"name":"陈刚"},
6     {"name":"郭丽丽"}
7 ])

1.2.3.数据查询

 1 from mongo_db import client
 2 
 3 try:
 4     teachers = client.school.teacher.find({})
 5     for one in teachers:
 6         print(one["_id"],one["name"])
 7     print("--------------------------")
 8     teacher=client.school.teacher.find_one({"name":"李璐"})
 9     print(teacher["_id"],teacher["name"])
10 except Exception as e:
11     print(e)

1.2.4.数据修改

 

1 from mongo_db import client
2 
3 try:
4     teachers = client.school.teacher.update_many({},{"$set":{"role":["班主任"]}})
5     teachers = client.school.teacher.update_one({"name":"李璐"},{"$set":{"sex":"女"}})
6     teachers = client.school.teacher.update_one({"name":"李璐"},{"$push":{"role":"年级主任"}})
7 except Exception as e:
8     print(e)

 

2.pymongo模块的删除操作

2.1.数据删除

 

类似删除操作:

1 from mongo_db import client
2 
3 try:
4     # client.school.teacher.delete_one({"name":"李璐"})   删除李璐这条记录
5     # client.school.teacher.delete_many({})     清空teacher集合
6     # client.school.student.update_one({"name":"lisi"},{"$unset":{"age":1}})    删除student集合中name为李四的记录的age属性
7     client.school.student.update_one({"name":"李强"},{"$pull":{"city":"天津"}})     #删除student集合中name为李强、属性为city、city中数据为天津的属性值
8 except Exception as e:
9     print(e)

 

2.2.其他操作总结

 1 from mongo_db import client
 2 
 3 try:
 4     #skip、limit分页查询
 5     students_top2 = client.school.student.find({}).skip(0).limit(2)
 6     for i in students_top2:
 7         print(i["_id"],i["name"])
 8 
 9     #查询不重复的学生姓名
10     students_name = client.school.student.distinct("name")
11     for i in students_name:
12         print(i)
13 
14     #根据属性name排序,1为升序,-1为降序
15     students_sort = client.school.student.find({}).sort([("name",-1)])
16     for i in students_sort:
17         print(i)
18 except Exception as e:
19     print(e)

 

3.pymongo模块向MongDB中保存文件

3.1.GridFS了解

 

 

3.2.连接GridFS

MongoDB对文件操作用的是GridFS引擎,因此我们需要连接GridFS,对MongoDB进行操作;

创建client连接并确定逻辑库即db,作为参数传入GridFS方法中,告诉GridFS对象连接已经创建好,连接的逻辑库是school,并且操作的是school中的book集合

GridFS(db,collection="book")

 

3.3.保存文件

使用GridFS的对象的put方法将文件写入到mongodb中

1 from mongo_db import client
2 from gridfs import GridFS
3 
4 db=client.school
5 gfs=GridFS(db,collection="book")
6 
7 with open("D:/MongoDB/111.pdf","rb") as f:
8     args={"type":"PDF","keyword":"111"}
9     gfs.put(f,filename="111.pdf",**args)

 

4.查询GridFS中存储的文件

4.1.查询文件

 1 import math
 2 
 3 from mongo_db import client
 4 from gridfs import GridFS
 5 
 6 db=client.school
 7 gfs=GridFS(db,collection="book")
 8 
 9 book=gfs.find_one({"filename":"111.pdf"})   #使用find函数根据filename属性值找到book集合中该文件
10 print(book.filename)        #打印文件的属性
11 print(book.type)
12 print(book.keyword)
13 print("%dM"%math.ceil(book.length/1024/1024))   #因为默认单位是字节,使用math方法转化成M

4.2.UTC转换成北京时间

UTC转换成北京时间

 1 import datetime
 2 import math
 3 from mongo_db import client
 4 from gridfs import GridFS
 5 
 6 db=client.school
 7 gfs=GridFS(db,collection="book")
 8 books=gfs.find({"type":"PDF"})
 9 for one in books:
10     #UTC转换成北京时间
11     uploadDate = one.uploadDate + datetime.timedelta(hours=8)
12     #格式化日期
13     uploadDate = uploadDate.strftime("%Y-%m-%d %H:%M:%S")
14     print(one._id,one.filename,uploadDate)

4.3.判断是否存储了文件

使用exists函数判断GridFS是否存储某个文件,存在返回True,不存在返回False;支持ID以及其他属性查找,要注意的是:

from mongo_db import client
from gridfs import GridFS
from bson.objectid import ObjectId

db=client.school
gfs=GridFS(db,collection="book")
rs=gfs.exists(ObjectId("628cd523a4f1ae6cbbf1566a"))
print(rs)
rs=gfs.exists(**{"type":"PDF"})
print(rs)

5.读取/删除GridFS中存储的文件

5.1.读取文件

from mongo_db import client
from gridfs import GridFS
from bson.objectid import ObjectId

db=client.school
gfs=GridFS(db,collection="book")
document = gfs.get(ObjectId("628cd523a4f1ae6cbbf1566a"))
with open("D:/MongoDB/222.pdf","wb") as f:
    f.write(document.read())

5.2.删除文件

1 from mongo_db import client
2 from gridfs import GridFS
3 from bson.objectid import ObjectId
4 
5 db=client.school
6 gfs=GridFS(db,collection="book")
7 gfs.delete(ObjectId("628cd523a4f1ae6cbbf1566a"))

 

标签:school,name,Python,MongoDB,db,client,GridFS,import,交互
来源: https://www.cnblogs.com/gltou/p/16306106.html