1. mongodb 安装
2. mongodb 权限列表
权限角色 | 权限操作 |
---|---|
read | 允许用户读取指定数据库 |
readWrite | 允许用户读写指定数据库 |
dbAdmin | 允许用户在指定数据库中执行管理函数,如索引创建,删除,查看统计或者是访问system.profile |
userAdmin | 允许用户向system.users集合写入,可以在指定数据库中创建,删除和管理用户 |
clusterAdmin | 只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限 |
readAnyDatabase | 只在admin数据库中可用,赋予用户所有数据库的读权限 |
readWriteAnyDatabase | 只在admin数据库中可用,赋予用户所有数据库的读写权限 |
userAdminAnyDatabase | 只在admin数据库中可用,赋予用户所有数据userAdmin权限 |
dbAdminAnyDatabase | 只在admin数据库中可用,赋予用户所有数据dbAdmin权限 |
root | 只在admin数据库中可用,超级账号,超级权限 |
3.mongodb 用户创建管理员用户
3.1 创建db用户管理员
mongodb存在一个管理用户组,这个组为专门管理普通用户产生。管理员通常没有数据库读写权限,只有操作用户的权限,因此我们只需要赋予管理员userAdminAnyDatabase权限。
> use admin
switched to db admin
> db.system.users.find()
> db.createUser({user:"yusw_user_admin",pwd:"java",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Successfully added user: {
"user" : "yusw_user_admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> db.system.users.find()
{ "_id" : "admin.yusw_user_admin", "userId" : UUID("858662da-5380-4823-8fe1-280ac7e30ae7"), "user" : "yusw_user_admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "OvwwKg2hsqu7DB2KdmfGRw==", "storedKey" : "MjvJh6g5nJaCid7PaQn5HElROXI=", "serverKey" : "iJsViekni0NgWYvZuhp4q4dNcAQ=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "T46/QqshrscRfXs7C1OeC7h9X9Kb+8l5uoZ9aw==", "storedKey" : "FKj1NEfnFQMiDgaMG5NbLL5IZngaz7xykmGK0vXqnjA=", "serverKey" : "ucU8L1lGC/8rI+Q8z2E5NSvKhqc6pqN9/ynBzMYJ2TM=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
>
3.2 开启权限验证
默认情况下是mongodb是默认不启动权限认证的,但是在生产环境肯定是打开的。需要在启动配置文件中进行参数配置进行打开。修改 mongodb.conf
systemLog:
destination: file
path: "/usr/local/mongodb/data/logs/mongodb.log"
logAppend: true
storage:
dbPath: "/usr/local/mongodb/data/db"
journal:
enabled: true
processManagement:
fork: true
net:
bindIp: localhost,192.168.37.11
port: 27017
security:
authorization: enabled //开启权限校验
3.3 验证权限启动是否生效
可以看到在重启mongod 服务之后会发现,db.system.users.find() 无法执行,可以知道当前是没有进行认证操作的,所以无法展示出show users
[root@ysw bin]# ./mongod -f mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 2168
child process started successfully, parent exiting
[root@ysw bin]# ./mongo
MongoDB shell version v4.4.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("594ec4d0-4a73-4307-8135-87062923913e") }
MongoDB server version: 4.4.8
> use admin
switched to db admin
> db.system.users.find()
Error: error: {
"ok" : 0,
"errmsg" : "command find requires authentication",
"code" : 13,
"codeName" : "Unauthorized"
}
3.3 管理员用户登入
用户登入之后就可以对用户信息进行相关操作
> use admin
switched to db admin
> db.auth("yusw_user_admin","java")
1
> db.system.users.find()
{ "_id" : "admin.yusw_user_admin", "userId" : UUID("858662da-5380-4823-8fe1-280ac7e30ae7"), "user" : "yusw_user_admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "OvwwKg2hsqu7DB2KdmfGRw==", "storedKey" : "MjvJh6g5nJaCid7PaQn5HElROXI=", "serverKey" : "iJsViekni0NgWYvZuhp4q4dNcAQ=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "T46/QqshrscRfXs7C1OeC7h9X9Kb+8l5uoZ9aw==", "storedKey" : "FKj1NEfnFQMiDgaMG5NbLL5IZngaz7xykmGK0vXqnjA=", "serverKey" : "ucU8L1lGC/8rI+Q8z2E5NSvKhqc6pqN9/ynBzMYJ2TM=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
>
4. 管理员用户创建普通用户
mongodb的权限必须先有能操作用户的管理员用户,然后再由管理员用户来创建普通用户
4.1 创建数据库
语句: use [dbname]
use: 就是存在此数据库的时候就切换到指定数据库下,无数据库就创建数据库。
show databases: 为什么没有 db_yusw 这个库呢?因为现在mongodb存储分为两块,内存和磁盘,数据库信息是存入了内存,磁盘中并没有相关库信息,知道写入集合,存在数据之后才会同步到磁盘。
> use db_yusw
switched to db db_yusw
> show databases
admin 0.000GB
config 0.000GB
infodb 0.000GB
local 0.000GB
4.2 创建普通用户
语句:
db.createUser(
{
user: "xxx",
pwd: "xxx",
roles: [{
role: "xxx",
db: "xxx"
}]
})
可以看到,在不认证管理原用户的情况下是没法创建其他数据库的普通用户的
> use db_yusw
switched to db db_yusw
> show databases
> db.createUser({user:"yusw_user",pwd:"java",roles:[{role:"readWrite",db:"db_yusw"}]})
uncaught exception: Error: couldn't add user: command createUser requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1386:11
@(shell):1:1
> use admin
switched to db admin
> auth("yusw_admin_user","java")
uncaught exception: ReferenceError: auth is not defined :
@(shell):1:1
> db.auth("yusw_user_admin","java")
1
创建有readWrite和dbAdmin 权限的用户 yusw_user
> use db_yusw
switched to db db_yusw
> db.createUser({user:"yusw_user",pwd:"java",roles:[{role:"readWrite",db:"db_yusw"},{role:"dbAdmin",db:"db_yusw"}]})
Successfully added user: {
"user" : "yusw_user",
"roles" : [
{
"role" : "readWrite",
"db" : "db_yusw"
},
{
"role" : "dbAdmin",
"db" : "db_yusw"
}
]
}
> db.auth("yusw_user","java")
1
>
4.3 更新用户角色,用户密码,删除用户
注意:更新角色是采用覆盖模式的,如果是需要新加角色,要把之前的角色也带上。如果执行之后没有提示任何信息说明更新成功,推出重新连接即可
更新用户角色语句:
db.updateUser(“username”,{roles:[{role:“new role”,db:“xxx”},{}]})
更新用户密码方式一:
db.updateUser(“username”,{pwd:“new password”})
更新用户密码方式二:
db.changeUserPassword(“new username”,“new password”)
删除用户:必须是管理员用户具备userAdminAnyDatabase权限
db.dropUser(“username”)
5. 集合相关操作
简单理解:集合就是相当于关系型数据库中的表
5.1 创建集合
语句: db.createCollection(name,options)
name: 要创建的集合名称
options: 可选参数,指定内存大小及索引选项
字段 | 类型 | 描述 |
---|---|---|
capped | 布尔 | 可选参数:创建固定大小集合,当达到最大值覆盖最早的文档,为true时必须指定size |
autoindexid | 布尔 | 可选参数:为true时,自动为_id创建索引,默认false |
size | 数值 | 可选参数:配合capped使用 |
max | 数值 | 指定固定集合中包含文档的最大数量 |
> db.createCollection("collection1",{capped:true,size:1024000,autoindexid:true,max:1000})
5.2 删除集合
> show tables
collection1
> db.collection1.drop()
true
> show tables
>
6. 新增文档(insert)
6.1 插入单个文档
语法:db.collectionName.insert(document)
> db.user.insert({name:"张三",age:11,birth: new Date(),address:"湖北武汉"})
WriteResult({ "nInserted" : 1 })
> db.user.insert({name:"jack",age:12,birth: new Date(),address:"湖北",tags:["spring","juc","mq"]})
WriteResult({ "nInserted" : 1 })
> db.user.find()
{ "_id" : ObjectId("61310a74be32e90777289693"), "name" : "张三", "age" : 11, "birth" : ISODate("2021-09-02T17:31:32.565Z"), "address" : "湖北武汉" }
{ "_id" : ObjectId("61310afbbe32e90777289694"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:33:47.557Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
6.2 批量插入文档
语法:db.collectionName.insert([{document1},{document2}])
也可以使用insertMany
> db.user.insert([{name:"jack",age:12,birth: new Date(),address:"湖北",tags:["spring","juc","mq"]},{name:"jack2",age:13,birth:new Date(),address:"湖北",tags:["spring","mq"]}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.user.find()
{ "_id" : ObjectId("61310a74be32e90777289693"), "name" : "张三", "age" : 11, "birth" : ISODate("2021-09-02T17:31:32.565Z"), "address" : "湖北武汉" }
{ "_id" : ObjectId("61310afbbe32e90777289694"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:33:47.557Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
{ "_id" : ObjectId("61310c3ebe32e90777289695"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:39:10.808Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
{ "_id" : ObjectId("61310cb9be32e90777289696"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:41:13.455Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
{ "_id" : ObjectId("61310cb9be32e90777289697"), "name" : "jack2", "age" : 13, "birth" : ISODate("2021-09-02T17:41:13.455Z"), "address" : "湖北", "tags" : [ "spring", "mq" ] }
>
6.3 通过变量值插入文档
定义变量:doc 只是一个变量名称可以随便起
doc = ({变量值})
db.collection.insert(doc)
> doc = ([{name:"lisi",age:13,birth: new Date(),address:"湖北1",tags:["spring","springcloud","juc","mq"]},{name:"jack3",age:13,birth:new Date(),address:"湖北",tags:["spring","mq"]}])
[
{
"name" : "lisi",
"age" : 13,
"birth" : ISODate("2021-09-02T17:45:54.857Z"),
"address" : "湖北1",
"tags" : [
"spring",
"springcloud",
"juc",
"mq"
]
},
{
"name" : "jack3",
"age" : 13,
"birth" : ISODate("2021-09-02T17:45:54.857Z"),
"address" : "湖北",
"tags" : [
"spring",
"mq"
]
}
]
> db.user.insert(doc)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.user.find()
{ "_id" : ObjectId("61310a74be32e90777289693"), "name" : "张三", "age" : 11, "birth" : ISODate("2021-09-02T17:31:32.565Z"), "address" : "湖北武汉" }
{ "_id" : ObjectId("61310afbbe32e90777289694"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:33:47.557Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
{ "_id" : ObjectId("61310c3ebe32e90777289695"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:39:10.808Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
{ "_id" : ObjectId("61310cb9be32e90777289696"), "name" : "jack", "age" : 12, "birth" : ISODate("2021-09-02T17:41:13.455Z"), "address" : "湖北", "tags" : [ "spring", "juc", "mq" ] }
{ "_id" : ObjectId("61310cb9be32e90777289697"), "name" : "jack2", "age" : 13, "birth" : ISODate("2021-09-02T17:41:13.455Z"), "address" : "湖北", "tags" : [ "spring", "mq" ] }
{ "_id" : ObjectId("61310deebe32e90777289698"), "name" : "lisi", "age" : 13, "birth" : ISODate("2021-09-02T17:45:54.857Z"), "address" : "湖北1", "tags" : [ "spring", "springcloud", "juc", "mq" ] }
{ "_id" : ObjectId("61310deebe32e90777289699"), "name" : "jack3", "age" : 13, "birth" : ISODate("2021-09-02T17:45:54.857Z"), "address" : "湖北", "tags" : [ "spring", "mq" ] }
>
7. 更新文档(update)
7.1 普通update
语法: db.collection.update({匹配条件},{更新内容},{更新参数})
这种update 是覆盖更新,会将所有字段都更新,不是更新某一字段
db.user.update({name:“张三”},{age:22})
> db.use