参考:mongoDB入门篇
1、对数据库的概念有比较清晰的认识。
2、了解一些简单的shell操作。
能学到什么?
1、了解mongoDB的特性
2、掌握mongoDB的基本操作
3、了解mongoDB在业务层的使用,并学会使用mongoDB来进行应用开发
现状
mongoDB:开源的NoSQL数据库
简介
- MongoDB的概念:mongo,MongoDB,索引,集合,复制集,分片,数据均衡
- 学会MongoDB的搭建:
- 熟悉MongoDB的使用
最基本的文档的读写更新删除
各种不同类型的索引的创建与使用
复杂的聚合查询
对数据集合进行分片,在不同分片间维持数据均衡
数据备份与恢复
数据迁移
- 简单运维
部署MongoDB集群
处理多种常见的故障:
单节点失效,如何恢复工作
数据库意外被杀死如何进行数据恢复
数据库发生拒绝服务时如何排查原因
数据库磁盘快满时如何处理。
相关网站
官网:www.mongodb.org
国内网站:www.mongoing.com
中文文档:docs.mongoing.com
github:https://github.com/mongodb
jira BUG提交及回复:https://jira.mongodb.org/
google 用户交流:mongodb-user,mongo-cn
数据库
概念:有组织的存放数据,按照不同需求进行查询
分类:
SQL数据库:支持Sql语言的数据库。Oracle,MySql
NnoSql数据库:不支持Sql语言的数据库。Redis,MongoDB
MongoDB的优点
1、无数据结构限制,每条记录都可以有不同的数据
2、完全的索引支持
redis的key-value
hbase的单索引,二级索引需要自己实现
单键索引,多键索引:{x:1,y:1}
数组索引:["apple","lemon"]
全文索引:"i am a little bird"(中文)
地理位置索引:2D
3、方便的冗余与扩展
复制集保证数据安全
分片扩展数据规模
4、良好的支持
完善的文档、良好的驱动
相关环境与工具
64位Linux
MongoDB: V2.5.6
SSH工具:xshell
文本编辑器:vim/notepad++
编译mongoDB文件
不太明白
搭建简单的mongoDB服务器
- 创建mongodb_simple目录,进入到目录中;
- 创建目录:data,用来存储数据库的数据文件。
- 创建目录:log,用来存储数据库的日志文件。
- 创建目录:bin,用来存储数据库的可执行文件。
- 创建目录:conf,用来存储数据库的配置文件。
我在Windows 64bit的环境下,
安装按照https://www.yiibai.com/mongodb/mongodb_quick_guide.html
注意:https://blog.youkuaiyun.com/Artful_Dodger/article/details/80844844
1、启动MongoDB服务。
start mongod --dbpath "D:/Program Files/MongoDB/Server/4.0/data" --logpath "D:/Program Files/MongoDB/Server/4.0/log/mongod.log" --logappend --install --serviceName "MongoDB"
或者:
net start MongodDB;
2、停止服务
net stop MongodDB;
连接mongoDB服务器
1、帮助:
mongo.exe --help
2、连接
mongo.exe 127.0.0.1:12345/test
D:\Program Files\MongoDB\Server\4.0\bin>mongo.exe 127.0.0.1:51882/test
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:51882/test
2018-09-26T17:34:49.781+0800 E QUERY [js] Error: couldn't connect to server 127.0.0.1:51882, conn
ection attempt failed: SocketException: Error connecting to 127.0.0.1:51882 :: caused by :: ����Ŀ���
��������ܾ��������ӡ� :
connect@src/mongo/shell/mongo.js:257:13
@(connect):1:6
exception: connect failed
3、关闭服务:
db.shutdownServer()
或者:
ps -ef/grep mongo => kill 进程号
两种方法关闭你之前开的数据库服务
taskkill /F /FI "IMAGENAME eq mongod.exe"
4、重新启动
numactl --interleave=all ${MONGODB_HOME}/bin/mongod --config conf/mongodb.conf
5、基本操作:
C:\Users\Administrator>mongo
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.2
Server has startup warnings:
2018-09-26T17:50:35.889+0800 I CONTROL [initandlisten]
2018-09-26T17:50:35.889+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled fo
r the database.
2018-09-26T17:50:35.889+0800 I CONTROL [initandlisten] ** Read and write access to data an
d configuration is unrestricted.
2018-09-26T17:50:35.889+0800 I CONTROL [initandlisten]
2018-09-26T17:50:35.889+0800 I CONTROL [initandlisten] Hotfix KB2731284 or later update is not inst
alled, will zero-out data files.
2018-09-26T17:50:35.889+0800 I CONTROL [initandlisten]
---
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
> use imooc
switched to db imooc
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
> use imooc
switched to db imooc
> db.dropDatabase()
{ "ok" : 1 }
> use imooc
switched to db imooc
> db.imooc_collection.insert({x:1})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
imooc 0.000GB
local 0.000GB
> show collections
imooc_collection
> db.imooc_collection.find()
{ "_id" : ObjectId("5bab5794c3ac4f3f6bd3d3bd"), "x" : 1 }
> db.imooc_collection.insert({x:2,_id:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_collection.insert({x:3,_id:1})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: imooc.imooc_collection index: _id
_ dup key: { : 1.0 }"
}
})
> db.imooc_collection.find({x:1})
{ "_id" : ObjectId("5bab5794c3ac4f3f6bd3d3bd"), "x" : 1 }
> for(i=3;i<100;i++)db.imooc_collection.insert({x:i})
WriteResult({ "nInserted" : 1 })
> db.imooc_collection.find()
{ "_id" : ObjectId("5bab5794c3ac4f3f6bd3d3bd"), "x" : 1 }
{ "_id" : 1, "x" : 2 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3be"), "x" : 3 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3bf"), "x" : 4 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c0"), "x" : 5 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c1"), "x" : 6 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c2"), "x" : 7 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c3"), "x" : 8 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c4"), "x" : 9 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c5"), "x" : 10 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c6"), "x" : 11 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c7"), "x" : 12 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c8"), "x" : 13 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c9"), "x" : 14 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3ca"), "x" : 15 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3cb"), "x" : 16 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3cc"), "x" : 17 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3cd"), "x" : 18 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3ce"), "x" : 19 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3cf"), "x" : 20 }
Type "it" for more
> db.imooc_collection.find().count()
99
> db.imooc_collection.find().skip(3).limit(2).sort({x:1})
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3bf"), "x" : 4 }
{ "_id" : ObjectId("5bab5845c3ac4f3f6bd3d3c0"), "x" : 5 }
>
更新
> db.imooc_collection.find({x:1});
{ "_id" : ObjectId("5bab5794c3ac4f3f6bd3d3bd"), "x" : 1 }
> db.imooc_collection.update({x:1},{x:999})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.imooc_collection.find({x:1});
> db.imooc_collection.find({x:999});
{ "_id" : ObjectId("5bab5794c3ac4f3f6bd3d3bd"), "x" : 999 }
>
-- 部分更新
> db.imooc_collection.update({z:100},{$set:{y:99}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.imooc_collection.find({z:100});
{ "_id" : ObjectId("5bac8895914aec091b494eff"), "x" : 100, "y" : 99, "z" : 100 }
>
更新不存在的数据
> db.imooc_collection.find({y:100})
> db.imooc_collection.update({y:100},{y:999})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
> db.imooc_collection.find({y:999})
> db.imooc_collection.update({y:100},{y:999},true)
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5bac8e2a69ac91ccf359afc1")
})
> db.imooc_collection.find({y:999})
{ "_id" : ObjectId("5bac8e2a69ac91ccf359afc1"), "y" : 999 }
>
更新多条数据
> db.imooc_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_collection.find({c:1})
{ "_id" : ObjectId("5bac94c8914aec091b494f00"), "c" : 1 }
{ "_id" : ObjectId("5bac94ca914aec091b494f01"), "c" : 1 }
{ "_id" : ObjectId("5bac94ca914aec091b494f02"), "c" : 1 }
> db.imooc_collection.update({c:1},{c:2})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.imooc_collection.find({c:1})
{ "_id" : ObjectId("5bac94ca914aec091b494f01"), "c" : 1 }
{ "_id" : ObjectId("5bac94ca914aec091b494f02"), "c" : 1 }
> db.imooc_collection.find({c:2})
{ "_id" : ObjectId("5bac94c8914aec091b494f00"), "c" : 2 }
> db.imooc_collection.update({c:1},{$set:{c:2}},false,true)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.imooc_collection.find({c:1})
> db.imooc_collection.find({c:2})
{ "_id" : ObjectId("5bac94c8914aec091b494f00"), "c" : 2 }
{ "_id" : ObjectId("5bac94ca914aec091b494f01"), "c" : 2 }
{ "_id" : ObjectId("5bac94ca914aec091b494f02"), "c" : 2 }
>
删除数据、删除表
> db.imooc_collection.remove()
2018-09-27T17:26:11.039+0800 E QUERY [js] Error: remove needs a query :
DBCollection.prototype._parseRemove@src/mongo/shell/collection.js:356:1
DBCollection.prototype.remove@src/mongo/shell/collection.js:383:18
@(shell):1:1
> db.imooc_collection.find({c:2})
{ "_id" : ObjectId("5bac94c8914aec091b494f00"), "c" : 2 }
{ "_id" : ObjectId("5bac94ca914aec091b494f01"), "c" : 2 }
{ "_id" : ObjectId("5bac94ca914aec091b494f02"), "c" : 2 }
> db.imooc_collection.remove({c:2})
WriteResult({ "nRemoved" : 3 })
> db.imooc_collection.find({c:2})
> db.imooc_collection.drop()
true
> show tables
>
创建索引
> show tables
> db.imooc_collection.getIndexes()
[ ]
> db.imooc_collection.insert({c:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_collection.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_collection"
}
]
> db.imooc_collection.ensureIndex({x:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
索引简介
种类与使用
匹配规则
如何建立合适的索引
索引建立的情况评估
索引的种类
- _id索引
- 单键索引
- 多键索引
- 复合索引
- 过期索引
- 全文索引
- 地理位置索引
_id索引
是绝大多数集合默认建立的索引
对于每个插入的数据,MongoDB都会自动生成一条唯一的_id字段。
> show tables
imooc_collection
> db.imooc_2.insert({x:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_2.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_2"
}
]
> db.imooc_2.findOne()
{ "_id" : ObjectId("5bad816aff6de6477dd2cbb5"), "x" : 1 }
单键索引
是最普通的索引
与_id索引不同,单键索引不会自动创建
例如:一条记录,形式为:{x:1,y:2,z:3}
> db.imooc_2.ensureIndex({x:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.imooc_2.getIndexes() })
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_2"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_2"
}
]
> db.imooc_2.findONe()
2018-09-28T09:31:40.111+0800 E QUERY [js] TypeError: db.imooc_2.findONe is not a function :
@(shell):1:1
> db.imooc_2.findOne()
{ "_id" : ObjectId("5bad816aff6de6477dd2cbb5"), "x" : 1 }
> db.imooc_2.find({x:1})
{ "_id" : ObjectId("5bad816aff6de6477dd2cbb5"), "x" : 1 }
多键索引
多键索引与单键索引创建形式相同,区别在于字段的值。
单键索引:值为一个单一的值,例如字符串,数字或者日期。
多键索引:值有多个记录,例如数组。
> db.imooc_2.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_2"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_2"
}
]
> db.imooc_2.find()
{ "_id" : ObjectId("5bad816aff6de6477dd2cbb5"), "x" : 1 }
> db.imooc_2.insert({x:1,y:2,z:3})
WriteResult({ "nInserted" : 1 })
> db.imooc_2.find()
{ "_id" : ObjectId("5bad816aff6de6477dd2cbb5"), "x" : 1 }
{ "_id" : ObjectId("5badbf16ff6de6477dd2cbb6"), "x" : 1, "y" : 2, "z" : 3 }
> db.imooc_2.insert({x:[1,2,3,4,5]})
WriteResult({ "nInserted" : 1 })
> db.imooc_2.find()
{ "_id" : ObjectId("5bad816aff6de6477dd2cbb5"), "x" : 1 }
{ "_id" : ObjectId("5badbf16ff6de6477dd2cbb6"), "x" : 1, "y" : 2, "z" : 3 }
{ "_id" : ObjectId("5badbf59ff6de6477dd2cbb7"), "x" : [ 1, 2, 3, 4, 5 ] }
复合索引
当我们的查询条件不只有一个时,就需要建立复合索引。
例如:按照x与y的值查询。创建索引,并查询
> db.imooc_2.ensureIndex({x:1,y:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
> db.imooc_2.find({x:1,y:2})
{ "_id" : ObjectId("5badbf16ff6de6477dd2cbb6"), "x" : 1, "y" : 2, "z" : 3 }
>
过期索引
是在一段时间后会过期的索引
在索引过期后,相应的数据会被删除。
这适合存储一些在一段时间之后会失效的数据比如用户的登录信息、存储的日志。
建立方法:
db.collection.ensureIndex({time:1},{expireAfterSeconds:10})
> db.imooc_2.ensureIndex({time:1},{expireAfterSeconds:30})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.imooc_2.insert({time:new Date()})
WriteResult({ "nInserted" : 1 })
> db.imooc_2.find()
{ "_id" : ObjectId("5badc837ff6de6477dd2cbb9"), "time" : ISODate("2018-09-28T06:20:39.628Z") }
> db.imooc_2.find()
{ "_id" : ObjectId("5badc837ff6de6477dd2cbb9"), "time" : ISODate("2018-09-28T06:20:39.628Z") }
> db.imooc_2.insert({time:new Date()})
WriteResult({ "nInserted" : 1 })
> db.imooc_2.find()
{ "_id" : ObjectId("5badc837ff6de6477dd2cbb9"), "time" : ISODate("2018-09-28T06:20:39.628Z") }
{ "_id" : ObjectId("5badc852ff6de6477dd2cbba"), "time" : ISODate("2018-09-28T06:21:05.996Z") }
> db.imooc_2.find()
{ "_id" : ObjectId("5badc852ff6de6477dd2cbba"), "time" : ISODate("2018-09-28T06:21:05.996Z") }
限制:
存储在过期索引字段的值必须是指定的时间类型。
必须是ISODate或者ISODate数组,不能使用时间戳,否则不能被自动删除。
如果指定了ISODate数组,则按照最小的时间进行删除。
过期索引不能是复合索引。
删除时间不是精确。(双层过程是由后台程序每60s跑一次,且删除需要时间,所以存在误差)
> db.imooc_2.insert({time:new Date()})
WriteResult({ "nInserted" : 1 })
> db.imooc_2.find()
{ "_id" : ObjectId("5badc8a1ff6de6477dd2cbbb"), "time" : 1 }
{ "_id" : ObjectId("5badc999ff6de6477dd2cbbc"), "time" : ISODate("2018-09-28T06:26:32.993Z") }
{ "_id" : ObjectId("5badc9a9ff6de6477dd2cbbd"), "time" : ISODate("2018-09-28T06:26:49.729Z") }
{ "_id" : ObjectId("5badc9b0ff6de6477dd2cbbe"), "time" : ISODate("2018-09-28T06:26:56.959Z") }
{ "_id" : ObjectId("5badc9b7ff6de6477dd2cbbf"), "time" : ISODate("2018-09-28T06:27:03.702Z") }
全文索引
对字符串与字符串数组创建全文可搜索的索引
适用情况:{author:"",title:"",article:""}
建立方法:
db.articles.ensureIndex({key:"text"})
db.articles.ensureIndex({key_1:"text",key_2:"text"})
db.articles.ensureIndex({"$**":"text"})
如何使用全文索引查询
db.articles.find({$text:{$search:"coffee"}})
db.articles.find({$text:{$search:"aa bb cc"}})--包含aa或bb或cc
db.articles.find({$text:{$search:"aa bb -cc"}}) --包含 aa bb,不包含cc
db.articles.find({$text:{$search:"\"aa\" \"bb\" \"cc\""}})--包含aa与bb与cc
> db.imooc_2.find({$text:{$search:"aa"}})
{ "_id" : ObjectId("5bade0f9ff6de6477dd2cbc2"), "article" : "aa bb dlskdlfjdlskjfd bb" }
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg" }
{ "_id" : ObjectId("5bade0e5ff6de6477dd2cbc0"), "article" : "aa bb cc dd ee" }
> db.imooc_2.find({$text:{$search:"rr"}})
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg" }
> db.imooc_2.find({$text:{$search:"aa bb cc"}})
{ "_id" : ObjectId("5bade0f9ff6de6477dd2cbc2"), "article" : "aa bb dlskdlfjdlskjfd bb" }
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg" }
{ "_id" : ObjectId("5bade0e5ff6de6477dd2cbc0"), "article" : "aa bb cc dd ee" }
> db.imooc_2.find({$text:{$search:"aa ee"}})
{ "_id" : ObjectId("5bade0f9ff6de6477dd2cbc2"), "article" : "aa bb dlskdlfjdlskjfd bb" }
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg" }
{ "_id" : ObjectId("5bade0e5ff6de6477dd2cbc0"), "article" : "aa bb cc dd ee" }
>
> db.imooc_2.find({$text:{$search:"aa bb -cc"}})
{ "_id" : ObjectId("5bade0f9ff6de6477dd2cbc2"), "article" : "aa bb dlskdlfjdlskjfd bb" }
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg" }
> db.imooc_2.find({$text:{$search:"\"aa\" \"bb\" \"cc\""}})
{ "_id" : ObjectId("5bade0e5ff6de6477dd2cbc0"), "article" : "aa bb cc dd ee" }
全文索引相似度查询
全文索引相似度
$meta操作符:{score:{$meta:"textScore"}}
写在查询条件后面可以返回返回结果的相似度。
与sort一起使用,可以达到很好的实用效果。
> db.imooc_2.find({$text:{$search:"aa bb"}},{score:{$meta:"textScore"}})
{ "_id" : ObjectId("5bade0e5ff6de6477dd2cbc0"), "article" : "aa bb cc dd ee", "score" : 1.2 }
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg", "score" : 1.25 }
{ "_id" : ObjectId("5bade0f9ff6de6477dd2cbc2"), "article" : "aa bb dlskdlfjdlskjfd bb", "score" : 1.
75 }
> db.imooc_2.find({$text:{$search:"aa bb"}},{score:{$meta:"textScore"}}).sort({score:{$meta:"textSco
re"}})
{ "_id" : ObjectId("5bade0f9ff6de6477dd2cbc2"), "article" : "aa bb dlskdlfjdlskjfd bb", "score" : 1.
75 }
{ "_id" : ObjectId("5bade0ecff6de6477dd2cbc1"), "article" : "aa bb rr gg", "score" : 1.25 }
{ "_id" : ObjectId("5bade0e5ff6de6477dd2cbc0"), "article" : "aa bb cc dd ee", "score" : 1.2 }
全文索引使用限制
每次查询,只能指定一个$text查询
$text查询不能出现在$nor查询中
查询中如果包含了$text,hint不再起作用。
现在还不支持中文。
索引属性——name指定
创建索引时的格式:db.collection.ensureIndex({param},{param})
第2个参数便是索引的属性。
重要的属性:
名字,name指定:db.collection.ensureIndex({},{name:""})
> db.imooc_6.ensureIndex({x:1})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.imooc_6.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_6"
}
]
> db.imooc_6.ensureIndex({y:-1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
> db.imooc_6.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"y" : -1
},
"name" : "y_-1",
"ns" : "imooc.imooc_6"
}
]
> db.imooc_6.ensureIndex({x:1,y:-1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 4,
"ok" : 1
}
> db.imooc_6.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"y" : -1
},
"name" : "y_-1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1,
"y" : -1
},
"name" : "x_1_y_-1",
"ns" : "imooc.imooc_6"
}
]
> db.imooc_6.ensureIndex({x:1,y:1,z:1,m:1},{name:"normal_index"})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 4,
"numIndexesAfter" : 5,
"ok" : 1
}
> db.imooc_6.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"y" : -1
},
"name" : "y_-1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1,
"y" : -1
},
"name" : "x_1_y_-1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1,
"y" : 1,
"z" : 1,
"m" : 1
},
"name" : "normal_index",
"ns" : "imooc.imooc_6"
}
]
> db.imooc_6.dropIndex("normal_index")
{ "nIndexesWas" : 5, "ok" : 1 }
唯一性:unique指定:db.collection.ensureIndex({},{unique:true/false})
> db.imooc_6.ensureIndex({m:1,n:1},{unique:true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 4,
"numIndexesAfter" : 5,
"ok" : 1
}
> db.imooc_6.insert({m:1,n:2})
WriteResult({ "nInserted" : 1 })
> db.imooc_6.insert({m:1,n:2})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: imooc.imooc_6 index: m_1_n_1 dup
key: { : 1.0, : 2.0 }"
}
})
、稀疏性,sparse指定:db.collection.ensureIndex({},{sparse:true/false})
不能查询不存在的索引。
> db.imooc_6.insert({m:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_6.insert({n:1})
WriteResult({ "nInserted" : 1 })
> db.imooc_6.find({m:{$exists:true}})
{ "_id" : ObjectId("5baf1dd0d1466f79b2df1571"), "m" : 1 }
{ "_id" : ObjectId("5baf1c0ad1466f79b2df156f"), "m" : 1, "n" : 2 }
> db.imooc_6.ensureIndex({m:1},{sparse:true})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 5,
"numIndexesAfter" : 6,
"ok" : 1
}
> db.imooc_6.find({m:{$exists:false}})
{ "_id" : ObjectId("5baf1dd4d1466f79b2df1572"), "n" : 1 }
> db.imooc_6.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1
},
"name" : "x_1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"y" : -1
},
"name" : "y_-1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"x" : 1,
"y" : -1
},
"name" : "x_1_y_-1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"unique" : true,
"key" : {
"m" : 1,
"n" : 1
},
"name" : "m_1_n_1",
"ns" : "imooc.imooc_6"
},
{
"v" : 2,
"key" : {
"m" : 1
},
"name" : "m_1",
"ns" : "imooc.imooc_6",
"sparse" : true
}
]
> db.imooc_6.find({m:{$exists:false}}).hint("m_1")
、是否定时删除,expireAfterSeconds指定:TTL,过期索引。
地理位置索引
概念:将一些点的位置存储在MongoDB中,创建索引后,可以按照位置来查找其他点。
子分类:
2d索引,用于存储和查找平面上的点。
2dsphere索引,用于存储和查找球面上的点。
查找方式:
查找距离某个点一定距离内的点。
查找包含在某区域内的点。
2d索引
平面地理位置索引
db.collection.ensureIndex({w:"2d"})
位置表示方式:经纬度 [经度,纬度]
取值范围:经度[-180,180] 纬度[-90,90]
查询方式:
$near查询:查询距离某个点最近的点。
$geoWithin查询:查询某个形状内的点。
形状的表示:
$box:矩形,使用:{$box:[[<x1>,<y1>],[<x2>,<y2>]]}表示。
$center:圆形,使用:{$center:[[<x1>,<y1>],r]}表示。
$polygon:多边形,使用{$polygon:[[<x1>,<y1>],[<x2>,<y2>],[<x3>,<y3>]]}表示
> db.location.ensureIndex({"w":"2d"})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.location.insert({w:[1,1]})
WriteResult({ "nInserted" : 1 })
> db.location.insert({w:[1,2]})
WriteResult({ "nInserted" : 1 })
> db.location.insert({w:[3,2]})
WriteResult({ "nInserted" : 1 })
> db.location.insert({w:[100,100]})
WriteResult({ "nInserted" : 1 })
> db.location.insert({w:[200,100]})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 13027,
"errmsg" : "point not in interval of [ -180, 180 ] :: caused by :: { _id: ObjectId('
5baf24ced1466f79b2df1577'), w: [ 200.0, 100.0 ] }"
}
})
> db.location.insert({w:[180,100]})
WriteResult({ "nInserted" : 1 })
> db.location.remove({w:[180,100]})
WriteResult({ "nRemoved" : 1 })
> db.location.insert({w:[180,80]})
WriteResult({ "nInserted" : 1 })
> db.location.find({w:{$near:[1,1]}})
{ "_id" : ObjectId("5baf24b2d1466f79b2df1573"), "w" : [ 1, 1 ] }
{ "_id" : ObjectId("5baf24b7d1466f79b2df1574"), "w" : [ 1, 2 ] }
{ "_id" : ObjectId("5baf24bbd1466f79b2df1575"), "w" : [ 3, 2 ] }
{ "_id" : ObjectId("5baf24c3d1466f79b2df1576"), "w" : [ 100, 100 ] }
{ "_id" : ObjectId("5baf24fed1466f79b2df1579"), "w" : [ 180, 80 ] }
> db.location.find({w:{$near:[1,1],$maxDistance:10}})
{ "_id" : ObjectId("5baf24b2d1466f79b2df1573"), "w" : [ 1, 1 ] }
{ "_id" : ObjectId("5baf24b7d1466f79b2df1574"), "w" : [ 1, 2 ] }
{ "_id" : ObjectId("5baf24bbd1466f79b2df1575"), "w" : [ 3, 2 ] }
> db.location.find({w:{$near:[1,1],$maxDistance:10,$minDistance:3}})
> db.location.find({w:{$near:[1,1],$maxDistance:10,$minDistance:2}})
{ "_id" : ObjectId("5baf24bbd1466f79b2df1575"), "w" : [ 3, 2 ] }
使用geoWithin查询
> db.location.find({w:{$geoWithin:{$box:[[0,0],[3,3]]}}})
{ "_id" : ObjectId("5baf24b2d1466f79b2df1573"), "w" : [ 1, 1 ] }
{ "_id" : ObjectId("5baf24b7d1466f79b2df1574"), "w" : [ 1, 2 ] }
{ "_id" : ObjectId("5baf24bbd1466f79b2df1575"), "w" : [ 3, 2 ] }
> db.location.find({w:{$geoWithin:{$box:[[1,1],[2,3]]}}})
{ "_id" : ObjectId("5baf24b2d1466f79b2df1573"), "w" : [ 1, 1 ] }
{ "_id" : ObjectId("5baf24b7d1466f79b2df1574"), "w" : [ 1, 2 ] }
> db.location.find({w:{$geoWithin:{$center:[[0,0],5]}}})
{ "_id" : ObjectId("5baf24b2d1466f79b2df1573"), "w" : [ 1, 1 ] }
{ "_id" : ObjectId("5baf24b7d1466f79b2df1574"), "w" : [ 1, 2 ] }
{ "_id" : ObjectId("5baf24bbd1466f79b2df1575"), "w" : [ 3, 2 ] }
> db.location.find({w:{$geoWithin:{$polygon:[[0,0],[0,1],[2,5],[6,1]]}}})
{ "_id" : ObjectId("5baf24b2d1466f79b2df1573"), "w" : [ 1, 1 ] }
{ "_id" : ObjectId("5baf24b7d1466f79b2df1574"), "w" : [ 1, 2 ] }
{ "_id" : ObjectId("5baf24bbd1466f79b2df1575"), "w" : [ 3, 2 ] }
使用geoNear查询
geoNear使用runCommand命令进行使用,使用如下:
db.runCommand(
{geoNear:<collection>,
near:[x,y],
minDistance:(对2d索引无效)
maxDistance:,
num:
...})
> db.runCommand({geoNear:"location",near:[1,2],maxDistance:10,num:1})
{
"results" : [
{
"dis" : 0,
"obj" : {
"_id" : ObjectId("5baf24b7d1466f79b2df1574"),
"w" : [
1,
2
]
}
}
],
"stats" : {
"nscanned" : 3,
"objectsLoaded" : 1,
"avgDistance" : 0,
"maxDistance" : 0,
"time" : 3753
},
"ok" : 1
}
> db.runCommand({geoNear:"location",near:[1,2],maxDistance:10,num:2})
{
"results" : [
{
"dis" : 0,
"obj" : {
"_id" : ObjectId("5baf24b7d1466f79b2df1574"),
"w" : [
1,
2
]
}
},
{
"dis" : 1,
"obj" : {
"_id" : ObjectId("5baf24b2d1466f79b2df1573"),
"w" : [
1,
1
]
}
}
],
"stats" : {
"nscanned" : 32,
"objectsLoaded" : 2,
"avgDistance" : 0.5,
"maxDistance" : 1,
"time" : 2919
},
"ok" : 1
}
2dsphere索引详解
球面地理位置索引
创建方式:db.collection.ensureIndex({w:"2dsphere"})
位置表示方式:
GeoJSON:描述一个点,一条直线,多边形等形状。
格式:{type:"",coordinates:[<coordinates>]}
查询方式:与2d索引查询方式类似,支持$minDistance与$maxDistance
索引构建情况分析
索引好处 | 索引缺点 |
---|---|
加快索引相关的查询 | 增加磁盘空间消耗,降低写入性能 |
如何评判当前索引构建情况:
1、mongostat工具介绍
2、profile集合介绍
3、日志介绍
4、explain分析
mongostat工具
查看mongodb运行状态的程序。
使用说明:mongostat -h 127.0.0.1:27017
字段说明:
索引情况:idx miss
for(i=0;i<100000;i++)db.imooc_62.insert({x:i})
--写入
D:\Program Files\MongoDB\Server\4.0>mongostat -h 127.0.0.1:27017
insert query update delete getmore command dirty used flushes vsize res qrw arw net_in net_out conn
time
1094 *0 *0 *0 0 2|0 0.1% 0.1% 0 923M 116M 0|0 1|0 171k 111k 2
Sep 30 14:26:51.212
1099 *0 *0 *0 0 1|0 0.2% 0.2% 0 923M 117M 0|0 1|0 172k 111k 2
Sep 30 14:26:52.213
1063 *0 *0 *0 0 1|0 0.2% 0.2% 0 923M 117M 0|0 1|1 166k 110k 2
Sep 30 14:26:53.213
关于profile集合
> db.getProfilingStatus()
{ "was" : 0, "slowms" : 100, "sampleRate" : 1 }
> db.get
imooc.get
-- 按TAB键
> db.get
imooc.get
> db.get
db.getCollection( db.getMongo( db.getRoles(
db.getCollectionInfos( db.getName( db.getSession(
db.getCollectionNames( db.getPrevError( db.getSiblingDB(
db.getFreeMonitoringStatus( db.getProfilingLevel( db.getSisterDB(
db.getLastError( db.getProfilingStatus( db.getSlaveOk(
db.getLastErrorCmd( db.getQueryOptions( db.getUser(
db.getLastErrorObj( db.getReplicationInfo( db.getUsers(
db.getLogComponents( db.getRole( db.getWriteConcern(
> db.getProfilingLevel()
0
> db.getProfilingStatus()
{ "was" : 0, "slowms" : 100, "sampleRate" : 1 }
> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 100, "sampleRate" : 1, "ok" : 1 }
> show tables
imooc_2
imooc_6
imooc_62
imooc_collection
location
> db.system.profile.find()
> db.system.profile.find().sort({$natural})
2018-09-30T14:36:24.595+0800 E QUERY [js] ReferenceError: $natural is not defined :
@(shell):1:32
> db.system.profile.find().sort({$natural:-1}).limit(10)
{ "op" : "query", "ns" : "imooc.system.profile", "command" : { "find" : "system.profile", "filter" :
{ }, "lsid" : { "id" : UUID("063b7367-b9d3-4c9c-8318-14a6eef6d59c") }, "$db" : "imooc" }, "keysExa
mined" : 0, "docsExamined" : 0, "cursorExhausted" : true, "numYield" : 0, "nreturned" : 0, "locks" :
{ "Global" : { "acquireCount" : { "r" : NumberLong(1) } }, "Database" : { "acquireCount" : { "r" :
NumberLong(1) } }, "Collection" : { "acquireCount" : { "r" : NumberLong(1) } } }, "responseLength" :
109, "protocol" : "op_msg", "millis" : 10, "planSummary" : "COLLSCAN", "execStats" : { "stage" : "C
OLLSCAN", "nReturned" : 0, "executionTimeMillisEstimate" : 0, "works" : 2, "advanced" : 0, "needTime
" : 1, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "direct
ion" : "forward", "docsExamined" : 0 }, "ts" : ISODate("2018-09-30T06:36:03.032Z"), "client" : "127.
0.0.1", "appName" : "MongoDB Shell", "allUsers" : [ ], "user" : "" }
日志介绍
使用MongoDB3.4+Access control is not enabled for the database解决方案:
https://blog.youkuaiyun.com/q1056843325/article/details/70941697
关于explain
> db.imooc_62.find({x:1}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "imooc.imooc_62",
"indexFilterSet" : false,
"parsedQuery" : {
"x" : {
"$eq" : 1
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"x" : {
"$eq" : 1
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "USER-20171123OR",
"port" : 27017,
"version" : "4.0.2",
"gitVersion" : "fc1573ba18aee42f97a3bb13b67af7d837826b47"
},
"ok" : 1
}
> db.imooc_62.find({x:1}).explain("executionStats")
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "imooc.imooc_62",
"indexFilterSet" : false,
"parsedQuery" : {
"x" : {
"$eq" : 1
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"x" : {
"$eq" : 1
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 1,
"executionTimeMillis" : 118,
"totalKeysExamined" : 0,
"totalDocsExamined" : 100000,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"x" : {
"$eq" : 1
}
},
"nReturned" : 1,
"executionTimeMillisEstimate" : 60,
"works" : 100002,
"advanced" : 1,
"needTime" : 100000,
"needYield" : 0,
"saveState" : 781,
"restoreState" : 781,
"isEOF" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsExamined" : 100000
}
},
"serverInfo" : {
"host" : "USER-20171123OR",
"port" : 27017,
"version" : "4.0.2",
"gitVersion" : "fc1573ba18aee42f97a3bb13b67af7d837826b47"
},
"ok" : 1
}
> db.imooc_62.ensureIndex({x:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.imooc_62.find({x:100}).explain()
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "imooc.imooc_62",
"indexFilterSet" : false,
"parsedQuery" : {
"x" : {
"$eq" : 100
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"x" : 1
},
"indexName" : "x_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"x" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"x" : [
"[100.0, 100.0]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "USER-20171123OR",
"port" : 27017,
"version" : "4.0.2",
"gitVersion" : "fc1573ba18aee42f97a3bb13b67af7d837826b47"
},
"ok" : 1
}
> db.imooc_62.find({x:100}).explain("executionStats")
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "imooc.imooc_62",
"indexFilterSet" : false,
"parsedQuery" : {
"x" : {
"$eq" : 100
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"x" : 1
},
"indexName" : "x_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"x" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"x" : [
"[100.0, 100.0]"
]
}
}
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 1,
"executionTimeMillis" : 7,
"totalKeysExamined" : 1,
"totalDocsExamined" : 1,
"executionStages" : {
"stage" : "FETCH",
"nReturned" : 1,
"executionTimeMillisEstimate" : 0,
"works" : 2,
"advanced" : 1,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"docsExamined" : 1,
"alreadyHasObj" : 0,
"inputStage" : {
"stage" : "IXSCAN",
"nReturned" : 1,
"executionTimeMillisEstimate" : 0,
"works" : 2,
"advanced" : 1,
"needTime" : 0,
"needYield" : 0,
"saveState" : 0,
"restoreState" : 0,
"isEOF" : 1,
"invalidates" : 0,
"keyPattern" : {
"x" : 1
},
"indexName" : "x_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"x" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"x" : [
"[100.0, 100.0]"
]
},
"keysExamined" : 1,
"seeks" : 1,
"dupsTested" : 0,
"dupsDropped" : 0,
"seenInvalidated" : 0
}
}
},
"serverInfo" : {
"host" : "USER-20171123OR",
"port" : 27017,
"version" : "4.0.2",
"gitVersion" : "fc1573ba18aee42f97a3bb13b67af7d837826b47"
},
"ok" : 1
}
MongoDB安全
- 安全概览
- 物理隔离与网络隔离
- IP白名单隔离
- 用户名密码鉴权
安全概览
- 最安全的是物理隔离:不现实
- 网络隔离
- 防火墙隔离
- 用户名密码
开启权限认证
auth开启
auth=true
参考官网文档:https://docs.mongodb.com/manual/tutorial/enable-authentication/#user-administrator
参考其他人文档:https://www.cnblogs.com/mymelody/p/5906199.html
> show users
{
"_id" : "test.myTester",
"user" : "myTester",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "reporting"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.system.users.find()
> ^C
bye
D:\Program Files\MongoDB\Server\4.0\bin>net stop MongoDB
MongoDB Server 服务正在停止.
MongoDB Server 服务已成功停止。
D:\Program Files\MongoDB\Server\4.0\bin>net start MongoDB
MongoDB Server 服务正在启动 ..
MongoDB Server 服务已经启动成功。
D:\Program Files\MongoDB\Server\4.0\bin>mongo -port 12345
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:12345/
MongoDB server version: 4.0.2
> show dbs
2018-09-30T17:27:33.472+0800 E QUERY [js] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "command listDatabases requires authentication",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:67:1
shellHelper.show@src/mongo/shell/utils.js:876:19
shellHelper@src/mongo/shell/utils.js:766:15
@(shellhelp2):1:1
> db.auth("myUserAdmin","abc123")
Error: Authentication failed.
0
> db.auth("myUserAdmin", "abc123" )
Error: Authentication failed.
0
> use admin
switched to db admin
> db.auth("myUserAdmin", "abc123" )
1
keyfile开启
MongoDB创建用户
创建语法:createUser
{user:"<name>",
pwd:"<cleartext password>",
customData:{<any infomation>},
roles:[{role:"<role>",db:"<database>"}]
}
角色类型:内建类型(read,readWrite,dbAdmin,dbOwner,userAdmin)
> use imooc
switched to db imooc
> db.createUser({user:"imooc",pwd:"imooc",roles:[{role:"userAdmin",db:"admin"},{
role:"read",db:"test"}]})
Successfully added user: {
"user" : "imooc",
"roles" : [
{
"role" : "userAdmin",
"db" : "admin"
},
{
"role" : "read",
"db" : "test"
}
]
}
D:\Program Files\MongoDB\Server\4.0\bin>mongo --port 12345 -u "imooc" -p "imooc"
--authenticationDatabase "imooc"
MongoDB shell version v4.0.2
connecting to: mongodb://127.0.0.1:12345/
MongoDB server version: 4.0.2
> show tables
foo
> use imooc
switched to db imooc
> show tables
Warning: unable to run listCollections, attempting to approximate collection nam
es by parsing connectionStatus
> use test
switched to db test
> show tables
foo
> db.imooc.insert({x:1})
WriteCommandError({
"ok" : 0,
"errmsg" : "not authorized on test to execute command { insert: \"imooc\
", ordered: true, lsid: { id: UUID(\"5265ae3f-9298-4c18-8736-46739d57c64f\") },
$db: \"test\" }",
"code" : 13,
"codeName" : "Unauthorized"
})
> db.imooc.find()
用户角色详解
数据库角色:
集群角色:
备份角色:
其他特殊权限:
创建用户角色