MongoDB的增删改查
1.创建集合
例: db.createCollection(“student”)
2.查看集合
例: show collections
3.删除集合
例: db.student.drop()
4.查看集合记录数量
例: db.student.count()
5.查看数据空间容量
例: db.student.dataSize()
6.重命名集合
例: db.student.renameCollection(“stu”)
7.添加记录
例: db.student.save([
{name:“Jeff”,sex:“male”,age:24},
{name:“Levi”,sex"female",age:21}
])
8.查询(find函数可以从集合中提取记录,参数为查询条件,若无参数则为无条件查询)
例: db.student.find()
db.student.find({name:“Jeff”, sex:“male”})
9.可以利用skip()和limit()实现分页查询: (skip:起始位置,limit:偏移量)
例: db.student.find().limit(10)
db.student.find().skip(20).limit(10)
10.sort()函数可以用来对结果排序。1:升序,-1:降序。
例: db.student.find().sort({name : -1})
11.排除重复(distinct()函数代替find()函数查找不重复的记录):
例: db.student.distinct(“name”)
db.student.distinct(“name”).sort(function(){return 1}) [javascript中使用匿名函数来表示排序规则]
db.student.distinct(“name”).slice(0,5) [javascript中的分页函数。表示0-5]
12.update()和updateMany()函数能实现对记录的修改
例: db.collection.updateMany({condition},{$set:{data}})
ps:[第一个参数:查询条件(可以为空的json,但是不可以不写),第二个参数:修改的记录]
13. $unset : 可以删除记录中的字段
例: db.student.updateMany( { } , { $unset : { city : 1, tel : 1 } }) (1表示为真,即确认要删除,写成其他的数字无效)
14. $inc : 对某个字段值做加法运算
例: db.student.updateMany( { } , { $inc : {age : 2}})
15. $push : 可以向数组属性添加元素
例: db.teacher.update( {name:“jack”} , { $push: {role: “教务处主任”}})
16. $pull : 可以删除数组属性的元素
例: db.teacher.update( {name:“jack”} , { $pull: {role: “副校长”}})
17. remove()函数可以删除记录
例: db.student.remove({})
MongoDB的索引机制
因为MongoDB中存放了大量的数据,所以为了加快数据检索速度,需要为集合设置索引
例: db.collection.createIndex({keys : 1}, options)
db.student.getIndexes
db.student.dropIndexes
索引字段按升序排列,属性值为1;降序为-1
因为创建索引的过程会阻塞MongoDB,影响其他操作,background参数代表在空闲时创建索引.
例: db.student.createIndex({name : 1}, {background: true})
db.student.createIndex({name : 1}, {background: true, name: “Sid”})
唯一性索引只能创建在每个记录都含有的公共字段上,在非公共字段上不能创建索引
例: db.student.createIndex({name : 1}, {background: true, unique: true})
MongoDB与Python交互
MongoClient是MongoDB的客户端代理对象,可以用来执行增删改查操作,还内置了连接池
①连接到MongoDB:
client = MongoClient(host="localhost", port=27017)
client.admin.authenticate("admin", "123456")
②使用find()和find_one() 函数查询语句:
students = client.school.student.find({})
print(students)
for one in students:
print(one["_id"], one["name"])
teacher = client.school.teacher.find_one({"name": "Luu"})
print(teacher["_id"], teacher["name"])
③使用insert()和insert_many() 函数插入值:
client.school.teacher.insert_one({"name": "Luu"})
client.school.teacher.insert_many([
{"name": "Poopi"},
{"name": "Galaxy"}
])
④使用update_many()和update_one() 函数修改值:
client.school.teacher.update_many({}, {"$set": {"role": ["班主任"]}})
client.school.teacher.update_one({"name": "Luu"}, {"$set": {"sex": "male"}})
client.school.teacher.update_one({"name": "Luu"},{"$push": {"role": "校长"}})
⑤使用delete_one()和delete_many() 函数删除数据:
client.school.teacher.delete_one({"name": "Luu"})
client.school.teacher.delete_many({})
⑥使用sort()和distinct() 函数对数据进行排序(注意sort和distinct的不同用法、参数):
students = client.school.student.find({}).skip(0).limit(10)
stu_name = client.school.student.distinct("name")
stu_sort = client.school.student.find().sort([("name", -1)])
pymongo模块向MongoDB中保存文件
①连接GridFS:默认情况下MongoClient不提供操作GridFS,需要创建GridFS对象
from pymongo import MongoClient
from gridfs import GridFS
client = MongoClient(host="localhost", port=27017)
client.admin.authenticate("admin", "123456")
db = client.school
gfs = GridFS(db, collection="book")
②put()函数可以把文件存储到GridFS中
from mongo_db import client
from gridfs import GridFS
db = client.school
gfs = GridFS(db, collection="book")
file = open("D:/Data/math5.pdf", "rb")
args = {"type": "PDF", "keyword": "math"}
gfs.put(file, filename="math5.pdf", **args)
file.close()
③find()和find_one() 函数可以查询GridFS中存储的文件
book = gfs.find_one({"filename": "math5.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:
# UTC(格林尼治时间)转换成北京时间:
uploadDate = one.uploadDate + datetime.timedelta(hours=8)
# 格式化日期
uploadDate = uploadDate.strftime("%Y-%m-%d %H:%M:%S")
print(one._id, one.filename, uploadDate)
④exists()函数可以判断GridFS是否存储某个文件
from bson.objectid import ObjectId
rs_1 = gfs.exists(ObjectId("5ce391a5acfdfab004bf8704"))
print(rs_1)
rs_2 = gfs.exists(**{"type": "PDF"})
print(rs_2)
⑤get() 函数可以从GridFS中读取文件,并且只能通过主键查找文件
from gridfs import GridFS
from bson.objectid import ObjectId
db = client.school
gfs = GridFS(db, collection="book")
document = gfs.get(ObjectId("5ce391a5acfdfab004bf8704"))
print("document.read:{0}".format(document.read()))
file = open("D:/Data/math6.pdf", "wb")
file.write(document.read())
file.close()
⑥delete() 函数可以从GridFS中删除文件,并且只能通过主键先查找记录
from gridfs import GridFS
from bson.objectid import ObjectId
db = client.school
gfs = GridFS(db, collection="book")
gfs.delete(ObjectId("5ce391a5acfdfab004bf8704"))
MongoDB数据的导入导出
-u : 用户名 -p : 密码 --authenticationDatabase : 账户隶属的逻辑库
-d : (导入/导出的)逻辑库 -c : 需要备份的集合 -f : 需要备份的集合中的记录(不写代表备份全部)
-o : 备份保存的地址 --file : 需要导入的文件地址
–drop : 把原有的逻辑库已有的数据删除
MongoDB表达式
MongoDB设置登录账户
首先要切换到admin逻辑库,然后创建root角色账户
use admin
db.createUser({
user:"admin",
pwd:"123456",
roles:[{role:"root",db:"admin"}]
})
MongoDB内置角色: