您的位置:首页 > 数据库 > Mongodb

Python | Python交互之mongoDB交互详解

2021-01-03 22:39 881 查看

前言

本篇为mongodb篇,包含实例演示,mongodb高级查询,mongodb聚合管道,python交互等内容。

mongoDB的优势

  • 易扩展

  • 大数据量,高性能

  • 灵活的数据模型

安装与启动

安装mongodb:sudo apt-get install -y mongodb-org
安装可视化管理界面:https://robomongo.org/download

查看帮助:mongod –help
启动服务:sudo service mongod start
停止服务:sudo service mongod stop
重启服务:sudo service mongod restart
查看进程:ps ajx|grep mongod

配置文件的位置:/etc/mongod.conf
默认端口:27017
日志的位置:/var/log/mongodb/mongod.log

mongodb数据库操作

数据库操作

查看当前的数据库: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()

mongodb数据类型

Object ID:文档ID

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个字节是简单的增量值

mongodb数据操作

新增

插入数据(字段_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"})

mongodb高级查询

mongodb查询方法

查询文档:db.集合名称.find({条件文档})
查询一条数据:db.集合名称.findOne({条件文档})
格式化查询:db.集合名称.find({条件文档}).pretty()

举个栗子:

# 查询name为xianyuplus的数据
db.xianyu.find({name:"xianyuplus"})

# 查询一条name为xianyuplus的数据
db.xianyu.findOne({name:"xianyuplus"})

mongodb的比较运算符

等于:如上述栗子
大于:$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}})

mongodb逻辑运算符

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"})

mongodb范围运算符

使用$in与$nin判断是否在某一范围内

举个栗子:

#查询年龄为18、28的数据
db.xianyu.find({age:{$in:[]18,28}})

mongodb使用正则表达式

使用//或$regex编写正则表达式

举个栗子:

# 查询name以xian开头的数据
db.xianyu.find({name:/^xianyu/})
db.xianyu.find({name:{$regex:'^xianyu'}})

mongodb分页与跳过

查询前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)

mongodb自定义查询

使用$where自定义查询,这里使用的是js语法

举个栗子:

//查询age大于30的数据
db.xianyu.find({
$where:function() {
return this.age>30;}
})

mongodb投影

投影:在查询结果中只显示你想要看到的数据字段内容。

db.集合名称.find({},{字段名称:1,...})

想显示的字段设置为1,不想显示的字段不设置,而_id这个字段比较特殊,想要他不显示需要设置_id为0。

#查询结果中只显示name字段,不显示age
db.xianyu.find({},{name:1})

mongodb排序

排序:db.集合名称.find().sort({字段:1,...})

将需要排序的字段设置值:升序为1,降序为-1

举个栗子:

#先按照性别降序排列再按照年龄升序排列
db.xianyu.find().sort({gender:-1,age:1})

mongodb计数

统计数目:db.集合名称.find({条件}).count()
db.集合名称.count({条件})

举个栗子:

#查询age为20的数据个数
db.xianyu.find({age:20}).count()
#查询age大于20,且性别为nan的数据个数
db.xianyu.count({age:{$gt:20},gender:true})

mongodb去重

去重:db.集合名称.distinct('去重字段',{条件})

举个栗子:

#去除家乡相同,且年龄大于18的数据
db.xianyu.distinct('hometown',{age:{$gt:18}})

mongodb管道与聚合

聚合(aggregate)是基于数据处理的聚合管道,每个文档通过一个由多个阶段(stage)组成的管道,可以对每个阶段的管道进行分组、过滤等功能,然后经过一系列的处理,输出相应的结果。

用法:db.集合名称.aggregate({管道:{表达式}})

常用管道:

$group: 将集合中的文档分组, 可用于统计结果
$match: 过滤数据, 只输出符合条件的文档
$project: 修改输出文档的结构, 如重命名、 增加、 删除字段、 创建计算结果
$sort: 将输出文档排序后输出
$limit: 限制聚合管道返回的文档数
$skip: 跳过指定数量的文档, 并返回余下的文档
$unwind: 将数组类型的字段进行拆分

常用表达式:表达式:"列名"

$sum: 计算总和, $sum:1 表示以一倍计数
$avg: 计算平均值
$min: 获取最小值
$max: 获取最大值
$push: 在结果文档中插入值到一个数组中
$first: 根据资源文档的排序获取第一个文档数据
$last: 根据资源文档的排序获取最后一个文档数据

聚合之$group

group:将文档进行分组以便于统计数目

用法:_id表示分组依据,_id:"$字段名"

举个栗子:

#按照hometown分组,并计数
db.xianyu.aggregate({$group:{_id:"$hometown", count:{$sum:1}}})

#将集合中所有的内容分为一组,统计个数
db.xianyu.aggregate({$group:{_id:null, count:{$sum:1}}})

聚合之$project

project:修改输入文档的结构,如:重命名,增加、删除字段等

举个栗子:

#按照hometown分组,并计数
#分组输出,只显示count字段
db.xianyu.aggregate(
{$group:{_id:"$hometown", count:{$sum:1}}},
{$project:{_id:0,count:1}}
)

聚合之$match

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

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

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

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

  • 能够同时按照多个键进行分组
    {$group:{_id:{country:"$字段",province:"$字段"}}}

mongodb索引

用法: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('索引名称')

mongodb数据备份与恢复

mongodb数据备份

备份:mongodump -h dbhost -d dbname -o dbdirectory

-h: 服务器地址,也可以指定端口号
-d: 需要备份的数据库名称
-o: 备份的数据存放位置,此目录中存放着备份出来的数据

mongodb数据恢复

恢复:mongorestore -h dbhost -d dbname --dir dbdirectory

-h: 服务器地址
-d: 需要恢复的数据库实例
--dir: 备份数据所在位置

mongodb与python交互

安装与导入

安装: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数据库交互的最后一篇,希望对你有所帮助。

推荐阅读

Python | Python学习之Redis交互详解

Python | Python学习之mysql交互详解

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: