一、安装mongodb
以windows平台示例,安装路径示例设置在c:\mongodb,https://www.mongodb.com/try/download/community官网下载msi安装包安装
- 安装MongoDB服务:
C:\mongodb\bin\mongod.exe --config "C:\mongodb\bin\mongod.cfg" --install
- 启动MongoDB服务:
net start MongoDB
- 关闭MongoDB服务:
net stop MongoDB
- 移除MongoDB服务:
C:\mongodb\bin\mongod.exe --remove
- 安装MongoDB服务使用的配置文件路径:
C:\mongodb\bin\mongod.cfg
,里面定义了数据存储路径、日志路径、端口等信息:
# Where and how to store data.
storage:
dbPath: C:\mongodb\data
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: C:\mongodb\log\mongod.log
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
二、基本操作
ObjectId类型说明
mongodb为每个文档创建_id属性,类型是ObjectId,保证文档唯一性
objectID是一个12字节的十六进制数:
- 前4个字节为当前时间戳
- 接下来3个字节是机器ID
- 接下来2个字节是MongoDB服务进程id
- 最后3个字节是简单的数字增量
创建数据库
use hellodb
无需显式创建,直接使用use
创建集合
db.createCollection("stu")
db.createCollection("stu",{capped:true,size:20})
capped:moren false表示不设置上限,true表示设置上限
size:当capped值为true需要指定此参数,表示上限大小,当文档达到上限时,会覆盖之前的数据**,单位是字节
tip:也可以不创建集合,直接插入文档,会自动创建集合
db.stu.insert({"name":"tom","age":12})
查看当前数据库的集合
show collections
删除数据库
use stu
db.dropDatabase()
删除集合
db.stu.drop()
查询
普通查询:
查询匹配条件的所有记录 db.stu.find()
find()里面可以加{xxx:xxx}查询条件
查询匹配到的第一条记录 db.stu.findOne({"name":"tom"})
运算符:
等于:db.stu.find({"age":12})
冒号: 就表示等于
大于等于:db.stu.find({"age":{$gte:12}})
其他的运算符还有$lte
、$ne
等
逻辑运算符:
与:db.stu.find({"name":"tom","age":12})
逗号, 就表示与
或:db.stu.find({$or:[{"name":"tom"},{"age":{$gt:13}}]})
#姓名等于tom或者年龄大于13
db.stu.find(
{
$or:[
{"name":"tom"},
{"age":
{$gt:13}
}
]
}
)
与、或同时使用:db.stu.find({$or:[{"name":"tom"},{"age":{$gte:12}}]})
范围查询:
age是否在[1,12,16]中:db.stu.find({age:{$in:[1,12,16]}})
正则查询:
查询姓名以'j'开头:
方式一:db.stu.find({name:/^j/})
方式二:db.stu.find({name:{$regex:'^j'}})
自定义查询,使用js函数查询:
db.stu.find({$where:function(){return this.age > 15}})
#this代表文档对象,function()需要返回布尔值
查询第4~5条数据:
db.stu.find().skip(3).limit(2)
#skip(3)跳过3条,limit(2)取2条。skip()和limit()顺序可以互换
查询结果显示某些字段:
db.stu.find({},{name:1,_id:0})
#第一个{}表示过滤条件,第二个{}表示属性是否显示,1显示,0隐藏
排序
db.stu.find().sort({name:-1,age:1})
#根据姓名倒序,姓名相同根据年龄升序。1表示升序,-1表示倒序
统计数量
方式一:db.stu.find({age:{$gte:16}}).count()
方式二:db.stu.count({age:{$gte:16}})
distinct去重
db.stu.distinct('name',{age:{$gt:10}}) #第一个是去重字段,第二个是过滤条件。不支持多字段去重!
[ "hanmeimei", "jerry", "lily", "tom" ]
更新数据(修改了文档结构)
> db.stu.find() #本来有两条name=tom的数据
{ "_id" : ObjectId("5f6154cf5929e0e305efcc0a"), "name" : "tom", "age" : 12 }
{ "_id" : ObjectId("5f61552a5929e0e305efcc0b"), "name" : "tom", "age" : 12 }
>
> db.stu.update({"name":"tom"},{"name":"jerry"}) #第一个字典是条件,第二个是要修改的结果。默认只会修改匹配到的第一个文档,并且修改了文档结构
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.stu.find()
{ "_id" : ObjectId("5f6154cf5929e0e305efcc0a"), "name" : "jerry" }
{ "_id" : ObjectId("5f61552a5929e0e305efcc0b"), "name" : "tom", "age" : 12 }
更新某个属性值(不会改变文档结构)
> db.stu.find()
{ "_id" : ObjectId("5f61580e5929e0e305efcc0c"), "name" : "tom", "age" : 12 }
{ "_id" : ObjectId("5f6158105929e0e305efcc0d"), "name" : "tom", "age" : 12 }
> db.stu.update({"name":"tom"},{$set:{"name":"jerry"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.stu.find()
{ "_id" : ObjectId("5f61580e5929e0e305efcc0c"), "name" : "jerry", "age" : 12 }
{ "_id" : ObjectId("5f6158105929e0e305efcc0d"), "name" : "tom", "age" : 12 }
上面两个更新都只更改了匹配到的第一条记录,如果要更改匹配到的多条记录,第三个参数传{multi:true}
按条件删除
> db.stu.find()
{ "_id" : ObjectId("5f61580e5929e0e305efcc0c"), "name" : "jerry", "age" : 12 }
{ "_id" : ObjectId("5f6158105929e0e305efcc0d"), "name" : "tom", "age" : 12 }
> db.stu.remove({age:12},{justOne:true}) #第一个参数是条件,第二个参数默认是false即会删除匹配到的所有记录,设为true只会删除匹配到的第一条记录
WriteResult({ "nRemoved" : 1 })
> db.stu.find()
{ "_id" : ObjectId("5f6158105929e0e305efcc0d"), "name" : "tom", "age" : 12 }
>
全部删除(谨慎操作)
sb.stu.remove({})
三、高级操作
聚合aggregate
aggregate主要用于计算数据,类似sql中的sum()、avg()
语法:db.集合名.aggregate([{管道:{表达式}}])
常用管道:
1、$group
:将集合中的文档分组,可用于统计结果
2、$match
:过滤数据,只输出符合条件的文档
3、$project
:修改输出文档的结构,如重命名、增加、删除字段、创建计算结果
4、$sort
:将输入文档排序后输出
5、$limit
:限制聚合管道返回的文档数
6、$skip
:跳过指定数量的文档,并返回余下的文档
7、$unwind
:将数组类型的字段进行拆分
常用表达式:
1、$sum
:计算总和,$sum:1
和count
一样表示计数
2、$avg
:计算平均值
3、$min
:获取最小值
4、$max
:获取最大值
5、$push
:结果插入一个数组中
6、$first
:获取第一个文档数据
7、$last
:获取最后一个文档数据
$group
用于分组
db.stu.aggregate([
{
$group:{
_id:"$gender", #_id是固定写法,后面加$字段名指定根据哪个字段分组。_id:null表示集合中所有文档分为一组
count:{$sum:1} #自定义名称count,$sum:1表示遇到一行就加一,用来统计数量
}
}
])
db.stu.aggregate([
{
$group:{
_id:"$gender", #_id是固定写法,后面$字段名指定根据哪个字段分组
count:{$sum:'$age'} #$age表示按照age字段求和,类似的还有平均值{$avg:'$age'}、最小值{$min:'$age'}、取第一个{$first:'$age'}
}
}
])
#按照性别分组,每组的所有年龄放到数组中
db.stu.aggregate([
{
$group:{
_id:"$gender",
count:{$push:'$age'}
}
}
])
>>>
/* 1 */
{
"_id" : "female",
"count" : [
14.0,
12.0
]
}
/* 2 */
{
"_id" : "male",
"count" : [
12.0,
13.0
]
}
#按照性别分组,每组的所有文档放到数组中
db.stu.aggregate([
{
$group:{
_id:"$gender",
count:{$push:'$$ROOT'}
}
}
])
>>>
/* 1 */
{
"_id" : "female",
"count" : [
{
"_id" : ObjectId("5f675abf1dd5b324a71b8985"),
"name" : "lily",
"age" : 14.0,
"gender" : "female"
},
{
"_id" : ObjectId("5f675aca1dd5b324a71b8986"),
"name" : "lisa",
"age" : 12.0,
"gender" : "female"
}
]
}
/* 2 */
{
"_id" : "male",
"count" : [
{
"_id" : ObjectId("5f675aac1dd5b324a71b8983"),
"name" : "tom",
"age" : 12.0,
"gender" : "male"
},
{
"_id" : ObjectId("5f675ab41dd5b324a71b8984"),
"name" : "jerry",
"age" : 13.0,
"gender" : "male"
}
]
}
$match
用于过滤数据
db.stu.aggregate([
{$match:{age:{$gt:12}}},#match的输入是原始文档,match的输出作为接下来group管道的输入
{$group:{
_id:'$gender',
counter:{$sum:1}
}}
])
>>>
/* 1 */
{
"_id" : "male",
"counter" : 1.0
}
/* 2 */
{
"_id" : "female",
"counter" : 1.0
}
$project
用来显示结果的部分数据,类似db.stu.find({},{name:1,_id:0})
#第一个{}表示过滤条件,第二个{}表示属性是否显示,1显示,0隐藏
db.stu.aggregate([
{$match:{age:{$gt:12}}},
{$group:{
_id:'$gender',
counter:{$sum:1}
}},#group的输出作为project的输入
{$project:{_id:0,counter:1}}
])
$sort
排序,1表示升序,-1表示降序
#按性别分组后,分组结果按人数排序
db.stu.aggregate([
{$group:{_id:'$gender',counter:{$sum:1}}},
{$sort:{counter:-1}}
])
>>>
/* 1 */
{
"_id" : "female",
"counter" : 3.0
}
/* 2 */
{
"_id" : "male",
"counter" : 2.0
}
$skip
、 $limit
$skip
表示跳过几条,$limit
表示取几条
#按照age倒序排序,跳过2条后取1条
db.stu.aggregate([
{$sort:{age:-1}},
{$skip:2},#$skip和$limit顺序不能变
{$limit:1}
])
$unwind
指定字段合到一起的数据分开显示
db.stu.aggregate([
{$group:{
_id:"$gender",
count:{$push:'$age'}
}},
{$unwind:'$count'}
])
>>>group之后的结果
/* 1 */
{
"_id" : "female",
"count" : [
14.0,
12.0
]
}
/* 2 */
{
"_id" : "male",
"count" : [
12.0,
13.0
]
}
>>>unwind之后的结果
/* 1 */
{
"_id" : "male",
"count" : 12.0
}
/* 2 */
{
"_id" : "male",
"count" : 13.0
}
/* 3 */
{
"_id" : "female",
"count" : 14.0
}
/* 4 */
{
"_id" : "female",
"count" : 12.0
}
/* 5 */
{
"_id" : "female",
"count" : 20.0
}
如果$unwind字段包含空,或者该字段不存在,查询结果会丢失:
#原始数据
/* 1 */
{
"_id" : 2.0,
"title" : "2",
"size" : []
}
/* 2 */
{
"_id" : 3.0,
"title" : "3"
}
/* 3 */
{
"_id" : 4.0,
"title" : "4",
"size" : null
}
/* 4 */
{
"_id" : 5.0,
"title" : "5",
"size" : "M"
}
#使用$unwind结构
db.stu2.aggregate([
{$unwind:'$size'}
])
/* 1 */
{
"_id" : 5.0,
"title" : "5",
"size" : "M"
}
防止丢失:
db.stu2.aggregate([
{$unwind:{path:'$size',preserveNullAndEmptyArrays:true}}
])
$lookup联表查询
订单表(order)和水果表(fruit)关联查询,表内容如下:
#订单表
/* 1 */
{
"_id" : 1.0,
"name" : "apple",
"price" : 3.5
}
/* 2 */
{
"_id" : 2.0,
"name" : "orange",
"price" : 4.0
}
/* 3 */
{
"_id" : 3.0
}
#水果表
/* 1 */
{
"_id" : 1.0,
"product" : "apple",
"quantity" : 100.0
}
/* 2 */
{
"_id" : 2.0,
"product" : "orange",
"quantity" : 200.0
}
/* 3 */
{
"_id" : 3.0,
"product" : null,
"quantity" : 300.0
}
/* 4 */
{
"_id" : 4.0
}
使用$lookup联表查询:
db.order.aggregate([
{ $lookup:
{
from: "fruit", #目标表名称
localField: "name",#当前表order要关联的字段
foreignField: "product",#目标表fruit要关联的字段
as: "fruit_list"#自定义结果字段
}
}
])
>>>
/* 1 */
{
"_id" : 1.0,
"name" : "apple",
"price" : 3.5,
"fruit_list" : [
{
"_id" : 1.0,
"product" : "apple",
"quantity" : 100.0
}
]
}
/* 2 */
{
"_id" : 2.0,
"name" : "orange",
"price" : 4.0,
"fruit_list" : [
{
"_id" : 2.0,
"product" : "orange",
"quantity" : 200.0
}
]
}
/* 3 */
{
"_id" : 3.0,
"fruit_list" : [
{
"_id" : 3.0,
"product" : null,
"quantity" : 300.0
},
{
"_id" : 4.0
}
]
}
1、查询结果的数量由当前表db.order.aggregate
即order
决定
2、输出结果中最后一条记录,order表_id:3
没有name字段,对应fruit表中 product:null或者没有product字段
索引操作
mongodb中的索引原理和mysql类似,索引是一种数据结构,能帮助我们快速查找,可以查看之前的mysql索引了解索引的原理。
创建10万条数据
for(i=0;i<100000;i++){
db.t1.insert({name:'test'+i,age:i})
}
查找姓名为test10000的文档,使用explain显示查找时间
db.t1.find({name:"test10000"}).explain("executionStats")
>>>
...
"executionTimeMillis" : 107, #耗时107毫秒
...
创建索引
db.t1.createIndex({name:1}) #基于姓名的索引
再次查询
db.t1.find({name:"test10000"}).explain("executionStats")
>>>
...
"executionTimeMillis" : 1, #耗时1毫秒
...
其他常用索引命令
- 查看当前所有索引:
db.t1.getIndexes()
/* 1 */
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"name" : 1.0
},
"name" : "name_1"
}
]
key是指index key的定义,包括两部分:key 和排序的方向
name是索引名称
v 标识index 版本,如果索引中包含"v":1,说明index是以新格式存储的,性能较高
- 唯一索引
db.t1.createIndex({"name":1},{"unique":true})
- 联合索引
db.t1.createIndex({name:1,age:1})
有了name和age联合索引,查找的时候就会快很多,db.t1.find({"name":"test10000","age":10000})
- 删除索引
db.t1.dropIndexes('name_1_age_1') #name_1_age_1是通过getIndexes()查询到的索引名称
四、mongo权限
常用角色:
- root:只在admin数据库中可用,具有任何数据库的读写权限
- Read:允许读指定数据库
- readWrite:允许读写指定数据库
先创建超级管理员:
use admin #必须使用admin数据库
db.createUser({
user:'tom',
pwd:'123',
roles:[{
role:'root',
db:'admin' #所属数据库
}]
})
查看添加的用户:
> use admin
switched to db admin
> show collections
system.users
system.version
> db.system.users.find().pretty()
{
"_id" : "admin.tom",
"userId" : UUID("8450c578-af02-4102-8301-f6bda63fde4d"),
"user" : "tom",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "vYgF3uoncJwWaJj7k7+Nbw==",
"storedKey" : "yBAm6gJ0IctKyw5NsG+p9takIaU=",
"serverKey" : "hF1KK8obAypBf+9JevlQIce7oPg="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "5gAlKtuQpaUx1rgRkRHd7Hc/az0Rm/A+i0yc9w==",
"storedKey" : "oqk8YexwpASytcDYGGaBfdNh41kroDXWGILPQTHWOBY=",
"serverKey" : "TerUGiUNOA3G4+i8knaW9j2sNvjcG5pdQEqeAhoXS3U="
}
},
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
>
卸载已有的服务
#以管理员身份打开dos窗口允许下面命令
C:\mongodb\bin\mongod.exe --remove
重新安装带认证的服务
#原来的安装服务命令后面加--auth,表示带认证
C:\mongodb\bin\mongod.exe --config "C:\mongodb\bin\mongod.cfg" --install --auth
#再启动服务
net start MongoDB
登录测试
#直接连接
C:\Windows\system32>mongo
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("6f80d0fb-c733-4df5-b64e-8e0c75ba67ff") }
MongoDB server version: 4.4.1
> show dbs
>
#通过超级管理员账号登录
#方法1 mongo ip:端口/数据库 -u 用户名 -p 密码
C:\Users\zh>mongo 127.0.0.1:27017/admin -u tom -p 123
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("0bf526e1-fd80-4827-982b-e17558ef737a") }
MongoDB server version: 4.4.1
---
The server generated these startup warnings when booting:
2020-10-04T08:21:50.779+08:00: ***** SERVER RESTARTED *****
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
#方法2 先登录,选择数据库,输入db.auth(用户名,密码)
C:\Users\zh>mongo
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("503186ef-db46-43fe-8d25-49c027a39232") }
MongoDB server version: 4.4.1
> show dbs
> use admin
switched to db admin
> db.auth('tom','123')
1
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
添加用户并设置权限
- 超级管理员下创建数据
> use shop
switched to db shop
>
> for(var i=1;i<=10;i++){
... db.goods.insert({"name":"goodsName"+i,"price":i})
... }
WriteResult({ "nInserted" : 1 })
> db.goods.find()
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5b"), "name" : "goodsName1", "price" : 1 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5c"), "name" : "goodsName2", "price" : 2 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5d"), "name" : "goodsName3", "price" : 3 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5e"), "name" : "goodsName4", "price" : 4 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5f"), "name" : "goodsName5", "price" : 5 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f60"), "name" : "goodsName6", "price" : 6 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f61"), "name" : "goodsName7", "price" : 7 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f62"), "name" : "goodsName8", "price" : 8 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f63"), "name" : "goodsName9", "price" : 9 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f64"), "name" : "goodsName10", "price" : 10 }
>
- 创建用户
> use shop
switched to db shop
> db.createUser({
... user:'shop1',
... pwd:'123',
... roles:[{
... role:'read',
... db:'shop'
... }]
... })
Successfully added user: {
"user" : "shop1",
"roles" : [
{
"role" : "read",
"db" : "shop"
}
]
}
>
>
> db.createUser({
... user:'shop2',
... pwd:'123',
... roles:[{
... role:'readWrite',
... db:'shop'
... }]
... })
Successfully added user: {
"user" : "shop2",
"roles" : [
{
"role" : "readWrite",
"db" : "shop"
}
]
}
>
- 查看已有用户
> use admin
switched to db admin
> db.system.users.find().pretty()
...
- 验证用户shop1可读不可写
C:\Users\zh>mongo 127.0.0.1:27017/shop -u shop1 -p 123
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/shop?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("08ec39cf-254a-4e41-8f88-c5c3478b90ca") }
MongoDB server version: 4.4.1
> show collections
goods
> db.goods.find()
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5b"), "name" : "goodsName1", "price" : 1 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5c"), "name" : "goodsName2", "price" : 2 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5d"), "name" : "goodsName3", "price" : 3 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5e"), "name" : "goodsName4", "price" : 4 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5f"), "name" : "goodsName5", "price" : 5 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f60"), "name" : "goodsName6", "price" : 6 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f61"), "name" : "goodsName7", "price" : 7 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f62"), "name" : "goodsName8", "price" : 8 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f63"), "name" : "goodsName9", "price" : 9 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f64"), "name" : "goodsName10", "price" : 10 }
> db.goods.insert({name:"abc",price:11})
WriteCommandError({
"ok" : 0,
"errmsg" : "not authorized on shop to execute command { insert: \"goods\", ordered: true, lsid: { id: UUID(\"08ec39cf-254a-4e41-8f88-c5c3478b90ca\") }, $db: \"shop\" }",
"code" : 13,
"codeName" : "Unauthorized"
})
- 验证用户shop2可读写
C:\Users\zh>mongo 127.0.0.1:27017/shop -u shop2 -p 123
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/shop?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("41d5b358-02cf-4d5c-921b-1b96a1377531") }
MongoDB server version: 4.4.1
> show collections
goods
> db.goods.find()
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5b"), "name" : "goodsName1", "price" : 1 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5c"), "name" : "goodsName2", "price" : 2 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5d"), "name" : "goodsName3", "price" : 3 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5e"), "name" : "goodsName4", "price" : 4 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f5f"), "name" : "goodsName5", "price" : 5 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f60"), "name" : "goodsName6", "price" : 6 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f61"), "name" : "goodsName7", "price" : 7 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f62"), "name" : "goodsName8", "price" : 8 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f63"), "name" : "goodsName9", "price" : 9 }
{ "_id" : ObjectId("5f79c55c7612dc57dce16f64"), "name" : "goodsName10", "price" : 10 }
> db.goods.insert({name:"abc",price:11})
WriteResult({ "nInserted" : 1 })
五、数据库备份还原
备份语法:mongodump -h -port -u -p -d -o
-h host 服务器ip,不写默认本机ip
-port 端口,不写默认27017
-u user 用户
-p password 密码
-d database 需要备份的数据库,不写导出全部
-o open 备份到指定目录下
备份所有数据库:
C:\Users\zh>mongodump -u tom -p 123 -o D:\mongo_backup
2020-10-07T08:32:49.854+0800 writing admin.system.users to D:\mongo_backup\admin\system.users.bson
2020-10-07T08:32:49.882+0800 done dumping admin.system.users (3 documents)
2020-10-07T08:32:49.883+0800 writing admin.system.version to D:\mongo_backup\admin\system.version.bson
2020-10-07T08:32:49.888+0800 done dumping admin.system.version (2 documents)
2020-10-07T08:32:49.888+0800 writing shop.goods to D:\mongo_backup\shop\goods.bson
2020-10-07T08:32:49.900+0800 done dumping shop.goods (11 documents)
备份指定数据库:
C:\Users\zh>mongodump -u tom -p 123 -d shop -o D:\mongo_backup
2020-10-07T08:36:13.054+0800 Failed: can't create session: could not connect to server: connection() : auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
#方法1:加上--authenticationDatabase admin指定admin数据库认证
C:\Users\zh>mongodump -u tom -p 123 --authenticationDatabase admin -d shop -o D:\mongo_backup
2020-10-07T08:50:41.196+0800 writing shop.goods to D:\mongo_backup\shop\goods.bson
2020-10-07T08:50:41.208+0800 done dumping shop.goods (11 documents)
#方法2:使用数据库对应的拥有读权限的用户,shop1、shop2都可以
C:\Users\zh>mongodump -u shop1 -p 123 -d shop -o D:\mongo_backup
2020-10-07T08:47:58.696+0800 writing shop.goods to D:\mongo_backup\shop\goods.bson
2020-10-07T08:47:58.706+0800 done dumping shop.goods (11 documents)
还原语法:mongorestore -h -port -u -p -d --drop 已备份的数据库目录
还原所有数据库
C:\Users\zh>mongorestore -u tom -p 123 --drop D:\mongo_backup
2020-10-07T09:02:28.746+0800 preparing collections to restore from
2020-10-07T09:02:28.774+0800 reading metadata for shop.goods from D:\mongo_backup\shop\goods.metadata.json
2020-10-07T09:02:29.058+0800 restoring shop.goods from D:\mongo_backup\shop\goods.bson
2020-10-07T09:02:29.076+0800 no indexes to restore
2020-10-07T09:02:29.076+0800 finished restoring shop.goods (11 documents, 0 failures)
2020-10-07T09:02:29.078+0800 reading metadata for stu.stu from D:\mongo_backup\stu\stu.metadata.json
2020-10-07T09:02:29.091+0800 restoring stu.stu from D:\mongo_backup\stu\stu.bson
2020-10-07T09:02:29.095+0800 no indexes to restore
2020-10-07T09:02:29.095+0800 finished restoring stu.stu (2 documents, 0 failures)
2020-10-07T09:02:29.095+0800 13 document(s) restored successfully. 0 document(s) failed to restore.
还原指定数据库:
C:\Users\zh>mongorestore -u tom -p 123 -d shop --drop D:\mongo_backup\shop
2020-10-08T07:22:29.102+0800 error connecting to host: could not connect to server: connection() : auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
#方法1:加上--authenticationDatabase admin指定admin数据库认证
C:\Users\zh>mongorestore -u tom -p 123 --authenticationDatabase admin -d shop --drop D:\mongo_backup\shop
2020-10-08T07:22:44.883+0800 The --db and --collection flags are deprecated for this use-case; please use --nsInclude instead, i.e. with --nsInclude=${DATABASE}.${COLLECTION}
2020-10-08T07:22:44.892+0800 building a list of collections to restore from D:\mongo_backup dir
2020-10-08T07:22:44.893+0800 don't know what to do with subdirectory "mongo_backup\shop", skipping...
2020-10-08T07:22:44.893+0800 don't know what to do with subdirectory "mongo_backup\stu", skipping...
2020-10-08T07:22:44.893+0800 0 document(s) restored successfully. 0 document(s) failed to restore.
#方法2:使用数据库对应的拥有写权限的用户认证
#用户shop没有写权限
C:\Users\zh>mongorestore -u shop -p 123 -d shop --drop D:\mongo_backup\shop
2020-10-08T07:26:40.815+0800 error connecting to host: could not connect to server: connection() : auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
#用户shop2可以恢复,因为有该数据库的写权限
C:\Users\zh>mongorestore -u shop2 -p 123 -d shop --drop D:\mongo_backup\shop
2020-10-08T07:26:45.939+0800 The --db and --collection flags are deprecated for this use-case; please use --nsInclude instead, i.e. with --nsInclude=${DATABASE}.${COLLECTION}
2020-10-08T07:26:45.948+0800 building a list of collections to restore from D:\mongo_backup\shop dir
2020-10-08T07:26:45.949+0800 reading metadata for shop.goods from D:\mongo_backup\shop\goods.metadata.json
2020-10-08T07:26:45.960+0800 restoring shop.goods from D:\mongo_backup\shop\goods.bson
2020-10-08T07:26:45.962+0800 no indexes to restore
2020-10-08T07:26:45.962+0800 finished restoring shop.goods (11 documents, 0 failures)
2020-10-08T07:26:45.962+0800 11 document(s) restored successfully. 0 document(s) failed to restore.
注意:在使用Robo3T可视化工具连接本地mongodb时会报错,需要手动指定认证用户: