本篇为mongodb篇,包含实例演示,mongodb高级查询,mongodb聚合管道,python交互等内容。python
易扩展mysql
大数据量,高性能正则表达式
安装mongodb:sudo apt-get install -y mongodb-org
安装可视化管理界面:https://robomongo.org/downloadsql
查看帮助:mongod –help
启动服务:sudo service mongod start
中止服务:sudo service mongod stop
重启服务:sudo service mongod restart
查看进程:ps ajx|grep mongodmongodb
配置文件的位置:/etc/mongod.conf
默认端口:27017
日志的位置:/var/log/mongodb/mongod.log数据库
查看当前的数据库:db
查看全部的数据库:show dbs /show databases
切换数据库:use db_name
删除当前的数据库:db.dropDatabase()数组
当集合不存在时,插入任何一条数据集合自动建立。
或者手动建立集合:db.createCollection(name,[options])
其中options:服务器
参数capped: 默认值为false表示不设置上限,值为true表示设置上限 参数size: 当capped值为true时,须要指定此参数,表示上限大小,当文档达到上限时,会将以前的数据覆盖,单位为字节
当集合存在时:
查看集合:show collections
删除集合:db.集合名称.drop()app
Object ID:文档IDless
String: 字符串,最常使用,必须是有效的UTF-8
Boolean: 存储一个布尔值,true或false
Integer: 整数能够是32位或64位,这取决于服务器
Double: 存储浮点值
Arrays: 数组或列表, 多个值存储到一个键
Object: 用于嵌入式的文档, 即一个值为一个文档
Null: 存储Null值
Timestamp: 时间戳,表示从1970-1-1到如今的总秒数
Date: 存储当前日期或时间的UNIX时间格式
注意点:
建立日期语句以下 :参数的格式为YYYY-MM-DD new Date('2017-12-20') 每一个文档都有一个属性,为_id,保证每一个文档的惟一性 能够本身去设置_id插入文档,若是没有提供,那么MongoDB为每一个⽂档提供了一个独特的_id,类型为objectID objectID是一个12字节的十六进制数: 前4个字节为当前时间戳 接下来3个字节的机器ID 接下来的2个字节中MongoDB的服务进程id 最后3个字节是简单的增量值
插入数据(字段_id存在就报错):db.集合名称.insert(document)
插入数据(字段_id存在就更新):db.集合名称.save(document)
举个栗子:
#插入文档时,若是不指定_id参数,MongoDB会为文档分配一个惟一的ObjectId db.xianyu.insert({name:"xianyuplus",age:"3"}) #插入文档时,能够指定_id参数 db.xianyu.insert({_id:"10001",name:"xianyuplus",age:"30"}) #更新了上面_id为1001的文档 db.xianyu.save({_id:"10001",name:"xianyuplus",age:"40"})
查询数据:db.集合名称.find()
举个栗子:
db.xianyu.find()
更新数据:db.集合名称.update(<query> ,<update>,{multi: <boolean>})
参数query:查询条件 参数update:更新操做符 参数multi:可选,默认是false,表示只更新找到的第一条记录,值为true表示把知足条件的文档所有更新
举个栗子:
原有内容: { "_id" : ObjectId("5b66f05f1194e110103bc283"), "name": "xianyuplus", "age": "40" } # 将name为xianyuplus的值替换为xianyuplus1 db.xianyu.update({name:"xianyuplus"},{name:"xianyuplus1"}) 操做后内容: { "_id" : ObjectId("5b66f05f1194e110103bc283"), "name": "xianyuplus1" }
能够看到单单使用update更新数据会致使原有数据被新数据替换,因此咱们应该搭配$set使用,指定更新对应的键值。
举个栗子:
原有内容: { "_id" : ObjectId("5b66f05f1194e110103bc283"), "name": "xianyuplus", "age": "40" } # 将name为xianyuplus的值更新为xianyuplus1 db.xianyu.update({name:"xianyuplus"},{$set:{name:"xianyuplus1"}}) 操做后内容: { "_id" : ObjectId("5b66f05f1194e110103bc283"), "name": "xianyuplus1", "age": "40" }
更新多条数据:使用参数multi:true
举个栗子:
# 更新所有数据的name值为xianyuplus1 db.stu.update({},{$set:{name:"xianyuplus1"}},{multi:true})
注意:multi update only works with $ operators 即multi只要和$搭配使用时才能起效。
删除数据:db.集合名称.remove(<query>,{justOne: <boolean>})
参数query:可选,删除的文档的条件 参数justOne:可选,若是设为true或1,则只删除一条,默认fals,表示删除多条
举个栗子:
# 把name值为xianyuplus的数据所有删掉 db.xianyu.remove({name:"xianyuplus"})
查询文档:db.集合名称.find({条件文档})
查询一条数据:db.集合名称.findOne({条件文档})
格式化查询:db.集合名称.find({条件文档}).pretty()
举个栗子:
# 查询name为xianyuplus的数据 db.xianyu.find({name:"xianyuplus"}) # 查询一条name为xianyuplus的数据 db.xianyu.findOne({name:"xianyuplus"})
等于:如上述栗子
大于:$gt ( greater than )
大于等于:$gte ( greater than equal )
小于:$lt ( less than )
小于等于:$lte ( less than equal )
不等于:$nt ( not equal )
举个栗子:
# 查询age大于20的数据 db.xianyu.find({age:{$gt:20}}) # 查询age大于等于20的数据 db.xianyu.find({age:{$gte:20}}) # 查询age小于20的数据 db.xianyu.find({age:{$lt:20}}) # 查询age小于等于20的数据 db.xianyu.find({age:{$lte:20}}) # 查询age不等于20的数据 db.xianyu.find({age:{$ne:20}})
and:在find条件文档中写入多个字段条件便可
or:使用$or
举个栗子:
#查找name为xianyuplus且age为20的数据 db.xianyu.find({name:"xianyuplus",age:20}) #查找name为xianyuplus或age为20的数据 db.xianyu.find({$or:[{name:"xianyuplus"},{age:20}]}) #查找name为xianyuplus或age大于20的数据 db.xianyu.find({$or:[{age:{$gt:20}},{name:"xianyuplus"}]}) #查找age大于等于20或gender为男而且name为xianyuplus的数据 db.xianyu.find({$or:[{gender:"true"},{age:{$gte:18}}],name:"xianyuplus"})
使用$in与$nin判断是否在某一范围内
举个栗子:
#查询年龄为1八、28的数据 db.xianyu.find({age:{$in:[]18,28}})
使用//或$regex编写正则表达式
举个栗子:
# 查询name以xian开头的数据 db.xianyu.find({name:/^xianyu/}) db.xianyu.find({name:{$regex:'^xianyu'}})
查询前n条数据:db.集合名称.find().limit(NUMBER)
跳过n条数据:db.集合名称.find().skip(NUMBER)
举个栗子:
#查询前3条数据 db.xianyu.find().limit(3) #查询3条后的数据 db.xianyu.find().skip(3) #skip和limit能够搭配使用,查询4,5,6条数据 db.xianyu.find().skip(3).limit(3)
使用$where自定义查询,这里使用的是js语法
举个栗子:
//查询age大于30的数据 db.xianyu.find({ $where:function() { return this.age>30;} })
投影:在查询结果中只显示你想要看到的数据字段内容。
db.集合名称.find({},{字段名称:1,...})
想显示的字段设置为1,不想显示的字段不设置,而_id这个字段比较特殊,想要他不显示须要设置_id为0。
#查询结果中只显示name字段,不显示age db.xianyu.find({},{name:1})
排序:db.集合名称.find().sort({字段:1,...})
将须要排序的字段设置值:升序为1,降序为-1
举个栗子:
#先按照性别降序排列再按照年龄升序排列 db.xianyu.find().sort({gender:-1,age:1})
统计数目:db.集合名称.find({条件}).count()
db.集合名称.count({条件})
举个栗子:
#查询age为20的数据个数 db.xianyu.find({age:20}).count() #查询age大于20,且性别为nan的数据个数 db.xianyu.count({age:{$gt:20},gender:true})
去重:db.集合名称.distinct('去重字段',{条件})
举个栗子:
#去除家乡相同,且年龄大于18的数据 db.xianyu.distinct('hometown',{age:{$gt:18}})
聚合(aggregate)是基于数据处理的聚合管道,每一个文档经过一个由多个阶段(stage)组成的管道,能够对每一个阶段的管道进行分组、过滤等功能,而后通过一系列的处理,输出相应的结果。
用法:db.集合名称.aggregate({管道:{表达式}})
经常使用管道:
$group: 将集合中的文档分组, 可用于统计结果 $match: 过滤数据, 只输出符合条件的文档 $project: 修改输出文档的结构, 如重命名、 增长、 删除字段、 建立计算结果 $sort: 将输出文档排序后输出 $limit: 限制聚合管道返回的文档数 $skip: 跳过指定数量的文档, 并返回余下的文档 $unwind: 将数组类型的字段进行拆分
经常使用表达式:表达式:"列名"
$sum: 计算总和, $sum:1 表示以一倍计数 $avg: 计算平均值 $min: 获取最小值 $max: 获取最大值 $push: 在结果文档中插入值到一个数组中 $first: 根据资源文档的排序获取第一个文档数据 $last: 根据资源文档的排序获取最后一个文档数据
group:将文档进行分组以便于统计数目
用法:_id表示分组依据,_id:"$字段名"
举个栗子:
#按照hometown分组,并计数 db.xianyu.aggregate({$group:{_id:"$hometown", count:{$sum:1}}}) #将集合中全部的内容分为一组,统计个数 db.xianyu.aggregate({$group:{_id:null, count:{$sum:1}}})
project:修改输入文档的结构,如:重命名,增长、删除字段等
举个栗子:
#按照hometown分组,并计数 #分组输出,只显示count字段 db.xianyu.aggregate( {$group:{_id:"$hometown", count:{$sum:1}}}, {$project:{_id:0,count:1}} )
match:用于过滤数据,只输出符合条件的文档,功能和find相似,可是match是管道命令,能将结果交给后一个管道,可是find不能够。
举个栗子:
#查询age大于20 #按照hometown分组,并计数 #分组输出,只显示count字段 db.xianyu.aggregate( {$match:{age:{$gte:20}}}, {$group:{_id:"$hometown", count:{$sum:1}}}, {$project:{_id:0,count:1}} )
sort:将输入文档排序后输出
举个栗子:
#查询age大于20 #按照hometown分组,并计数 #分组输出,只显示count字段 #按照计数升序排序 db.xianyu.aggregate( {$match:{age:{$gte:20}}}, {$group:{_id:"$hometown", count:{$sum:1}}}, {$project:{_id:0,count:1}}, {$sort:{count:1}} )
limit:限制聚合管道返回的文档数
skip:跳过指定数量的文档数,返回剩下的文档
举个栗子:
#查询age大于20 #按照hometown分组,并计数 #按照计数升序排序 #跳过前一个文档,返回第二个 db.xianyu.aggregate( {$match:{age:{$gte:20}}}, {$group:{_id:"$hometown", count:{$sum:1}}}, {$sort:{count:1}}, {$skip:1}, {$limit:1} )
unwind:将文档中的某一个数组类型字段拆分红多条, 每条包含数组中的一个值
db.集合名称.aggregate({$unwind:'$字段名称'})
举个栗子:
db.xianyu.insert({_id:1,item:'t-shirt',size:['S','M','L']}) db.xianyu.aggregate({$unwind:'$size'}) 输出: { "_id" : 1, "item" : "t-shirt", "size" : "S" } { "_id" : 1, "item" : "t-shirt", "size" : "M" } { "_id" : 1, "item" : "t-shirt", "size" : "L" }
$group对应的字典中有几个键,结果中就有几个键
分组依据须要放到_id后面
取不一样的字段的值须要使用$,$gender,$age
取字典嵌套的字典中的值的时候$_id.country
用法:db.集合.ensureIndex({属性:1}),1表示升序, -1表示降序
建立惟一索引:db.集合.ensureIndex({"属性":1},{"unique":true})
建立惟一索引并消除:
db.集合.ensureIndex({"属性":1},{"unique":true,"dropDups":true})
创建联合索引:db.集合.ensureIndex({属性:1,age:1})
查看当前集合的全部索引:db.集合.getIndexes()
删除索引:db.集合.dropIndex('索引名称')
备份:mongodump -h dbhost -d dbname -o dbdirectory
-h: 服务器地址,也能够指定端口号 -d: 须要备份的数据库名称 -o: 备份的数据存放位置,此目录中存放着备份出来的数据
恢复:mongorestore -h dbhost -d dbname --dir dbdirectory
-h: 服务器地址 -d: 须要恢复的数据库实例 --dir: 备份数据所在位置
安装:pip install pymongo
导入模块:from pymongo import MongoClient
实例化对象以连接数据库,链接对象有host,port两个参数。
from pymongo import MongoClient class clientMongo: def __init__(self): client = MongoClient(host="127.0.0.1", port=27017) #使用[]括号的形式选择数据库和集合 self.cliention = client["xianyu"]["xianyuplus"]
插入单条数据:返回ObjectId
def item_inser_one(self): ret = self.cliention.insert({"xianyu":"xianyuplus","age":20}) print(ret)
插入多条数据:
def item_insert_many(self): item_list = [{"name":"xianyuplus{}".format(i)} for i in range(10000)] items = self.cliention.insert_many(item_list)
查询单条数据:
def item_find_one(self): ret = self.cliention.find_one({"xianyu":"xianyuplus"}) print(ret)
查询多条数据:
def item_find_many(self):
ret = self.cliention.find({"xianyu":"xianyuplus"})
for i in ret:
print(i)
更新一条数据:
def item_update_one(self): self.cliention.update_one({"xianyu":"xianyuplus"},{"$set":{"xianyu":"xianyu"}})
更新所有数据:
def item_update(self): self.cliention.update_many({"xianyu":"xianyuplus"},{"$set":{"xianyu":"xianyu"}})
删除一条数据:
def item_delete_one(self): self.cliention.delete_one({"xianyu":"xianyuplus"})
删除符合条件的数据:
def item_delete_many(self): self.cliention.delete_many({"xianyu":"xianyuplus"})
以上就是关于mongodb的一些用法,重点部分仍是mongo高级查询以及聚合管道,必定要review几遍才记得住,本篇是python数据库交互的最后一篇,但愿对你有所帮助。