数据存储-MongoDB
MongoDB安装
非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似 JSON 对象,它的字段值可以包含其他文档、数组及文档数组
安装与启动
安装教程:https://zhuanlan.zhihu.com/p/596465307
下载地址:https://www.mongodb.com/try/download/community
使用文档:https://www.mongodb.org.cn/tutorial/55.html
使用教程2:
MongoDB:6.0.3
Mongosh: 1.6.2
win7
MongoDB 3.4.24
安装教程:https://blog.csdn.net/qq_27093465/article/details/54574948
mongod --config D:\LenovoSoftstore\mongo\mongo.conf --install --serviceName "MongoDB"
启动
net start MongoDB #启动 需管理员权限(服务端)
net stop MongoDB #关闭数据库
mongosh # 启动客户端 6.0.3
mongo # 启动客户端 3.4.24
#创建用户
#使用用户权限
exit() #退出
show dbs # 查看数据库
use Mydata #创建并进入数据库
db.Mydata.insert({"name":"google"}) #数据库插入数据
db.Mydata.find()
db.dropDatabase() #进入数据库后 删除
# 集合操作
show collections # 查看集合
db.createCollection("MyCollection") # 创建MyCollectionj集合
db.MyCollection.insert({'username':'jenny','age':20,'gender':300}); #向集合中插入一些数据
db.MyCollection.find() #查询集合内数据
db.MyCollection.drop() #删除集合
# MongoBulkWriteError: db already exists with different case already have: BulkWriteResult 暂未找到解决方法
MongoDB简单使用
# 数据
db.MyCollection.insert({'id':1,'name':'apple','age':20,'gender':true});
db.MyCollection.insert({'id':2,'name':'banana','age':20,'gender':false});
db.MyCollection.insert({'id':3,'name':'city','age':16,'gender':false});
db.MyCollection.insert({'id':4,'name':'delay','age':20,'gender':true});
db.MyCollection.insert({'id':5,'name':'effect','age':17,'gender':true});
db.MyCollection.insert({'id':6,'name':'finite','age':20,'gender':true});
db.MyCollection.insert({'id':7,'name':'guess','age':10,'gender':true});
# 增
db.MyCollection.insert({'username':'jenny','age':20,'gender':300});
dict_data = {
'id':1,
'name':'jenny',
'age':55,
'gender':true
}
db.MyCollection.insert(dict_data)
# 删
db.MyCollection.remove({'username':'jenny'}) #无效方法
db.MyCollection.deleteOne({'username':'zhangyu'}) #删一个
db.MyCollection.deleteMany({'gender':true}) #删多个
db.MyCollection.remove({}) #删所有数据
# 改
db.MyCollection.update({}); #无效方法
db.MyCollection.updateOne({id:7}, {$set: {name:'张三'}});
db.MyCollection.updateMany({gender:true}, {$set: {age:66}});
db.MyCollection.updateOne({id:1}, {$unset: {name:''}}); #去除某个key
# 查 简单
db.MyCollection.find() #查找所有
db.MyCollection.find({gender:false})
db.MyCollection.findOne({gender:false}) #查找一个
# 查 比较运算 $lt小于 $lte小于等于 $gt大于 $gte大于等于 $ne不等于
db.MyCollection.find({age:{$lte:17}})
db.MyCollection.find({age:{$ne:20}})
# 查 逻辑运算 $and $or 注意大括号
db.MyCollection.find({age:{$gt:17},gender:true}) #多条件 默认and
db.MyCollection.find({$and:[{age:{$lte:17}},{name:'guess'}]})
db.MyCollection.find({$or:[{age:{$lte:17}},{name:'guess'}]})
db.MyCollection.find({$or:[{age:{$lte:17},gender:true},{name:'guess'}]})# 混用
#查 范围运算 $in $nin
db.MyCollection.find({age:{$in:[10, 20]}})
db.MyCollection.find({age:{$nin:[10, 20]}})
#查 正则
db.MyCollection.find({name:{$regex:'^b'}})
db.MyCollection.find({name:{$regex:'^B',$options:'i'}}) # 忽略大小写
db.MyCollection.find({name:/^b/})
db.MyCollection.find({name:/^b/i}) # 忽略大小写
# 查 定义函数 js代码
db.MyCollection.find({
$where:function (){
return this.age<20
}
})
MongoDB 查询展示
# 看特定个数
db.MyCollection.find().limit(4) #前4个
db.MyCollection.find().skip(2) #跳过前两个
db.MyCollection.find().skip(2).limit(4)
db.MyCollection.find().skip(5).limit(4)
#投影 只看特定字段
db.MyCollection.find({}, {name:1,age:1})
#统计
db.MyCollection.find({gender:false}).count()
db.MyCollection.count({gender:false})
db.MyCollection.count()
db.MyCollection.find().count()
# 排序
db.MyCollection.find().sort({'age':1}) #升序
db.MyCollection.find().sort({'age':1,'id':-1})
# 去重
db.MyCollection.distinct('age',{范围与条件}) # 去重非删除数据,只是看数据分布范围
MongoDB复合查询
//aggregate 聚合查询
db.MyCollection.aggregate(
[
{管道1},
{管道2}]
)
db.MyCollection.aggregate([{$group:{_id:'$gender'}}]) //$group 分组
//$group 分组
//表达式 $sum $avg $max $min $first $last $push
db.MyCollection.aggregate([
{$group:{_id:'$gender', sumage:{$sum:'$age'}}} //按性别分组,计算分组后年龄之和 $sum求和
])
db.MyCollection.aggregate([
{$group:{_id:'$gender', avgage:{$avg:'$age'}}} //按性别分组,计算分组后平均年龄 $avg平均
])
db.MyCollection.aggregate([
{$group:{_id:'$gender', maxage:{$max:'$age'}, minage:{$min:'$age'}}} // $max最大值 $min最小值
])
db.MyCollection.aggregate([
{$group:{_id:'$gender', first_age:{$first:'$age'}, last_age:{$last:'$age'}}} // $first第一个 $last最后一个
])
db.MyCollection.aggregate([
{$group:{_id:'$gender', animate:{$push:'$age'}}} //按性别分组查看分组后年龄分布 $push分布
])
//$match == find find不能使用管道传递
db.MyCollection.aggregate([
//年龄20的人有哪些 与find效果相同
{$match:{'age':20}}
])
db.MyCollection.aggregate([
//求年龄大于15 的男女平均年龄
{$match:{'age':{$gt:15}}},
{$group:{_id:'$gender',avgage:{$avg:'$age'}}}
])
//$project 投影
db.MyCollection.aggregate([
// $只显示年龄之和
{$match:{'age':{$gt:15}}},
{$group:{_id:'$gender', maxage:{$max:'$age'}, minage:{$min:'$age'}}},
{$project:{minage:1}}
])
//$sort 排序
db.MyCollection.aggregate([
{$sort:{'age':-1}}// $年龄降序
])
//skip limit
db.MyCollection.aggregate([
{$skip:2},
{$limit:3}, //3,4,5
])
db.MyCollection.aggregate([
{$limit:3},
{$skip:2}, //3
])
//unwind 拆分
db.MyCollection.aggregate([
{$group:{_id:'$gender',allname:{$push:'$name'}}},//男女分组及分组后的名字
{$unwind:"$allname"} //拆分
])
//混用
db.MyCollection.aggregate([
{$match:{'age':{$gt:15}}},//相当于筛选
{$group:{_id:'$gender', maxage:{$max:'$age'}, minage:{$min:'$age'}}},//相当于分组
{$project:{minage:1}},//相当之查看特定字段
{$sort:{'minage':-1}}//相当于排序
])
MongoDB索引查询
for(var i=0;i<=500000;i++){
db.data.insert({
_id:i,
user:'user'+i,
age:i
})
}
db.data.find({_id:250000}).explain('executionStats') //速度最快 1ms
db.data.find({user:'user250000'}).explain('executionStats')// 300ms
db.data.find({age:250000}).explain('executionStats')//200ms
//开发中设置内容的key为id,提高查询速度
db.data.ensureIndex({user:1})
db.data.find({user:'user250000'}).explain('executionStats') //速度提升 2ms
db.data.getIndexes() //查看所有索引
db.data.dropIndex('user_1')//删除索引
MongoDB备份与恢复
命令行运行
//备份
mongodump -h 127.0.0.1:27017 -d local -o C:\Users\Administrator\Desktop\beifen
//恢复
mongorestore -h 127.0.0.1:27017 -d beifen --dir C:\Users\Administrator\Desktop\beifen\local
//导出文件
mongoexport -h 127.0.0.1:27017 -d beifen -c MyCollection -o data.json // c Administrator
mongoexport -h 127.0.0.1:27017 -d beifen -c MyCollection -o data.csv --type csv -f id,user,age,gender
//导入文件
mongoimport -h 127.0.0.1:27017 -d beifen -c stu --file data.json
MongoDB与Python
# MongoDB 3.4.24
# pymongo 3.2
import pymongo
try:
# 1、链接mongodb的服务
mongo_py = pymongo.MongoClient()
# 2、库和表的名字
# db = mongo_py['ku']
# collection = db['biao']
collection= mongo_py['ku']['biao']
# 3、插入数据
one = {'name':'apple','age':20}
two_many = [
{'name': 'banana', 'age': 20},
{'name': 'city', 'age': 30},
{'name': 'day', 'age': 40},
{'name': 'egg', 'age': 50},
]
# collection.insert_one(one)
# collection.insert(one) #支持一条和多条
# collection.insert_many(two_many)
# collection.delete_one({'age':20})
# collection.delete_many({'age': {'$in': [30, 40]}})
# collection.update_one({'age': 20}, {'$set': {'name': 'zig'}})
# collection.update_many({'age': 20}, {'$set': {'name': 'zig'}})
result = collection.find({'age':20})
print(result[0])
except Exception as err:
print(str(err))
finally:
# 4、关闭数据库
mongo_py.close()