mongodb之用户管理与系统管理常用命令

简介:

## mongodb的用户管理(认证管理)

  • 用户分三种    

       全局用户

         数据库对应用户

         只读用户


### 创建全局用户(全局用户只能在admin账户下创建)

  • 创建了一个名为zhuima,密码为zhuima的全局账户


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@redis ~]# hostname
redis.unix178.com
[root@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> show dbs
local0.078125GB
> use admin
switched to db admin
> db.addUser("zhuima","zhuima")
{
"user" : "zhuima",
"readOnly" : false,
"pwd" : "214c77cbc6bc7d26f28022c30496223d",
"_id" : ObjectId("53cbcb3cc5761ac13c7f6614")
}
>


### 开启配置文件中的auth = true选项

1
2
3
4
5
[root@redis ~]# sed -n '/auth/p' /etc/mongodb.conf
#noauth = true
#auth = true
auth = true
[root@redis ~]#


### 重启mongodb进行验证 这里可以看到我们进行show的时候提示没权限

1
2
3
4
5
6
[root@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> show dbs
Sun Jul 20 14:02:01.765 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46
>


### test数据库是默认进入的目录,如果你不想进入test数据库,mongo 后面跟上--nodb即可

### 想要切换到全局用户时,必须先要进入admin数据库才可以

1
2
3
4
5
6
7
8
9
10
11
[root@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> use admin
switched to db admin
> db.auth("zhuima","zhuima")
1
> show dbs
admin0.203125GB
local0.078125GB
>


### 创建对应数据库的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
> use zhuima
switched to db zhuima
> info = {info = {Name:"zhuima",Age:26,Gender:"F",Address:"Beijing China",Work:"Engineer",Other:"DevOps"}
... 
... 
> info = {Name:"zhuima",Age:26,Gender:"F",Address:"Beijing China",Work:"Engineer",Other:"DevOps"}
{
"Name" : "zhuima",
"Age" : 26,
"Gender" : "F",
"Address" : "Beijing China",
"Work" : "Engineer",
"Other" : "DevOps"
}
> db.addUser("nick","zhuima")
{
"user" : "nick",
"readOnly" : false,
"pwd" : "79e274165fd09b1902705535f24eecf9",
"_id" : ObjectId("53cbcd00a6852f086df7d087")
}


### 可以看出nick用户只能对zhuima这个数据库进行权限操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[root@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> use zhuima
switched to db zhuima
> db.auth("nick","zhuima")
1
> show dbs
Sun Jul 20 14:08:02.743 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46
> show collections
system.indexes
system.users
> db.system.users.find()
{ "_id" : ObjectId("53cbcd00a6852f086df7d087"), "user" : "nick", "readOnly" : false, "pwd" : "79e274165fd09b1902705535f24eecf9" }
> info = {Name:"zhuima",Age:26,Gender:"F",Address:"Beijing China",Work:"Engineer",Other:"DevOps"}
{
"Name" : "zhuima",
"Age" : 26,
"Gender" : "F",
"Address" : "Beijing China",
"Work" : "Engineer",
"Other" : "DevOps"
}
> db.student.insert(info)
> db.student.find()
{ "_id" : ObjectId("53cbcd71d89972ce7ecf83c1"), "Name" : "zhuima", "Age" : 26, "Gender" : "F", "Address" : "Beijing China", "Work" : "Engineer", "Other" : "DevOps" }
>


### 增加一个只读用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
> db.addUser("kale","zhuima",True)
Sun Jul 20 14:10:33.956 ReferenceError: True is not defined
> db.addUser("kale","zhuima",true)
{
"user" : "kale",
"readOnly" : true,
"pwd" : "c705496ba883d8a8acf0855396fa8b5e",
"_id" : ObjectId("53cbcde3d89972ce7ecf83c2")
}
> message = {Name:"kale",Age:26,Gender:"F"}
{ "Name" : "kale", "Age" : 26, "Gender" : "F" }
> db.auth("kale","zhuima")
1
> message = {Name:"kale",Age:26,Gender:"F"}
{ "Name" : "kale", "Age" : 26, "Gender" : "F" }
> show collections
student
system.indexes
system.users
> db.student.insert(message)
not authorized for insert on zhuima.student
> db.auth("nick","zhuima")
1
> db.student.insert(message)
> db.student.find()
{ "_id" : ObjectId("53cbcd71d89972ce7ecf83c1"), "Name" : "zhuima", "Age" : 26, "Gender" : "F", "Address" : "Beijing China", "Work" : "Engineer", "Other" : "DevOps" }
{ "_id" : ObjectId("53cbce5fd89972ce7ecf83c4"), "Name" : "kale", "Age" : 26, "Gender" : "F" }
>


### 删除一个用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
> db.system.users.find()
{ "_id" : "admin.zhuima", "user" : "zhuima", "db" : "admin", "credentials" : { "MONGODB-CR" : "214c77cbc6bc7d26f28022c30496223d" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "zhuima.nick", "user" : "nick", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "b8b8d091c8b634fe785f41cf3339d9ec" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }
{ "_id" : "zhuima.test", "user" : "test", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "a6de521abefc2fed4f5876855a3484f5" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }
{ "_id" : "zhuima.kale", "user" : "kale", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "a47cb6627c18898317171265eeea47e2" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }
> use zhuima
switched to db zhuima
> db.dropUser("test")
true
> show collections
person
system.indexes
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : "admin.zhuima", "user" : "zhuima", "db" : "admin", "credentials" : { "MONGODB-CR" : "214c77cbc6bc7d26f28022c30496223d" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "zhuima.nick", "user" : "nick", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "b8b8d091c8b634fe785f41cf3339d9ec" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }
{ "_id" : "zhuima.kale", "user" : "kale", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "a47cb6627c18898317171265eeea47e2" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }
>


### 用户管理后记

  • 多用help 类似db.help()

  • 看官方文档,然后把命令都敲一遍

  • 多实践才是王道




## 来一些系统的基本的查看管理命令


### help指令

  • 多用help,你会发现原来世界那么美好

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
> help
db.help()                    help on db methods
db.mycoll.help()             help on collection methods
sh.help()                    sharding helpers
rs.help()                    replica set helpers
help admin                   administrative help
help connect                 connecting to a db help
help keys                    key shortcuts
help misc                    misc things to know
help mr                      mapreduce
show dbs                     show database names
show collections             show collections in current database
show users                   show users in current database
show profile                 show most recent system.profile entries with time >= 1ms
show logs                    show the accessible logger names
show log [name]              prints out the last segment of log in memory, 'global' is default
use < db_name >                set current database
db.foo.find()                list objects in collection foo
db.foo.find( { a : 1 } )     list objects in foo where a == 1
it                           result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x   set default number of items to display on shell
exit                         quit the mongo shell
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]
db.auth(username, password)
db.cloneDatabase(fromhost)
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.createUser(userDocument)
db.currentOp() displays currently executing operations in the db
db.dropDatabase()
db.eval(func, args) run code server-side
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSlaveReplicationInfo()
db.dropUser(username)
db.repairDatabase()
db.resetError()
db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
db.serverStatus()
db.setProfilingLevel(level,< slowms >) 0=off 1=slow 2=all
db.setWriteConcern( < write  concern doc> ) - sets the write concern for writes to the db
db.unsetWriteConcern( < write  concern doc> ) - unsets the write concern for writes to the db
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
>

### 查看当前所在数据库位置

  • 第一种方式

1
2
3
4
> db.status
admin.status
>
  • 第二种方式

1
2
3
> db.getName();
admin
>


### 当前数据库版本

1
2
3
> db.version()
2.6.3
>


### 查看当前数据库中的包含的集合

1
2
3
4
> show collections
system.indexes
system.users
system.version


### 删除数据库

  • 切换到该数据库目录下,进行drop操作即可

1
2
3
4
5
6
7
8
9
10
11
12
> show dbs
admin   0.078GB
local   1.078GB
zhuima  0.078GB
> use zhuima
switched to db zhuima
> db.dropDatabase()
{ "dropped" : "zhuima", "ok" : 1 }
> show dbs
admin  0.078GB
local  1.078GB
>



### 查看各collection的状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
> use admin
switched to db admin
>  db.printCollectionStats()
system.indexes
{
"ns" : "admin.system.indexes",
"count" : 3,
"size" : 336,
"avgObjSize" : 112,
"storageSize" : 8192,
"numExtents" : 1,
"nindexes" : 0,
"lastExtentSize" : 8192,
"paddingFactor" : 1,
"systemFlags" : 0,
"userFlags" : 1,
"totalIndexSize" : 0,
"indexSizes" : {
},
"ok" : 1
}
---
system.users
{
"ns" : "admin.system.users",
"count" : 3,
"size" : 720,
"avgObjSize" : 240,
"storageSize" : 8192,
"numExtents" : 1,
"nindexes" : 2,
"lastExtentSize" : 8192,
"paddingFactor" : 1,
"systemFlags" : 1,
"userFlags" : 1,
"totalIndexSize" : 16352,
"indexSizes" : {
"_id_" : 8176,
"user_1_db_1" : 8176
},
"ok" : 1
}
---
system.version
{
"ns" : "admin.system.version",
"count" : 1,
"size" : 48,
"avgObjSize" : 48,
"storageSize" : 8192,
"numExtents" : 1,
"nindexes" : 1,
"lastExtentSize" : 8192,
"paddingFactor" : 1,
"systemFlags" : 1,
"userFlags" : 1,
"totalIndexSize" : 8176,
"indexSizes" : {
"_id_" : 8176
},
"ok" : 1
}
---
>

 

  

### 查看collection数据的大小

1
2
3
> db.system.users.dataSize()
720
>


### 增删查改的文章请移步到上篇文章



本文转自lovelace521 51CTO博客,原文链接:http://blog.51cto.com/lovelace/1441033,如需转载请自行联系原作者

相关文章
|
9月前
|
NoSQL MongoDB 微服务
微服务——MongoDB常用命令——文档的分页查询
本文介绍了文档分页查询的相关内容,包括统计查询、分页列表查询和排序查询。统计查询使用 `count()` 方法获取记录总数或按条件统计;分页查询通过 `limit()` 和 `skip()` 方法实现,控制返回和跳过的数据量;排序查询利用 `sort()` 方法,按指定字段升序(1)或降序(-1)排列。同时提示,`skip()`、`limit()` 和 `sort()` 的执行顺序与编写顺序无关,优先级为 `sort()` &gt; `skip()` &gt; `limit()`。
338 1
|
9月前
|
JSON NoSQL MongoDB
微服务——MongoDB常用命令——文档基本CRUD
本文介绍了MongoDB中文档的基本操作,包括插入、查询、更新和删除。单个文档插入使用`insert()`或`save()`方法,批量插入用`insertMany()`。查询所有文档用`find()`,条件查询可在`find()`中添加参数,投影查询控制返回字段。更新文档通过`update()`实现,支持覆盖修改、局部修改(使用`$set`)和批量修改。列值增长可用`$inc`实现。删除文档用`remove()`,需谨慎操作以免误删数据。此外,文档键值对有序,区分大小写,不能有重复键。
208 1
|
9月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令——MongoDB索引知识概述
本文介绍MongoDB索引相关知识,包括其在查询中的重要作用。索引可避免全集合扫描,显著提升查询效率,尤其在处理海量数据时。通过B树数据结构存储字段值并排序,支持相等匹配、范围查询及排序操作。文中还提供了官方文档链接以供深入学习。
159 0
|
9月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令——MongoDB索引的类型
本节介绍了MongoDB中索引的几种类型及其特点。包括单字段索引,支持升序/降序排序,索引顺序对操作无影响;复合索引,字段顺序重要,可实现多级排序;地理空间索引,支持平面与球面几何查询;文本索引,用于字符串搜索并存储词根;哈希索引,基于字段值散列,适合等值匹配但不支持范围查询。
230 1
微服务——MongoDB常用命令——MongoDB索引的类型
|
9月前
|
存储 JSON NoSQL
MongoDB常用命令
本文介绍了将文章评论数据存储到MongoDB中的操作方法,包括数据库和集合的基本操作。主要内容涵盖:选择与创建数据库(如`articledb`)、数据库删除、集合的显式与隐式创建及删除、文档的CRUD操作(插入、查询、更新、删除)。此外,还详细说明了分页查询、排序查询以及统计查询的方法,例如使用`limit()`、`skip()`实现分页,`sort()`进行排序,`count()`统计记录数。通过实例展示了如何高效管理MongoDB中的数据。
|
9月前
|
NoSQL 关系型数据库 MongoDB
微服务——MongoDB常用命令——集合操作
本节主要介绍MongoDB中的集合操作,包括显式与隐式创建集合的方法。显式创建使用`db.createCollection(name)`,需遵循命名规范(如不能以&quot;system.&quot;开头或包含`\0`字符)。隐式创建则通过直接向不存在的集合插入文档实现,更为常用。此外,还介绍了集合删除方法`db.collection.drop()`及其返回值规则,帮助用户管理数据库中的集合资源。
342 0
|
9月前
|
存储 NoSQL MongoDB
微服务——MongoDB常用命令1——数据库操作
本节介绍了 MongoDB 中数据库的选择、创建与删除操作。使用 `use 数据库名称` 可选择或创建数据库,若数据库不存在则自动创建。通过 `show dbs` 或 `show databases` 查看所有可访问的数据库,用 `db` 命令查看当前数据库。注意,集合仅在插入数据后才会真正创建。数据库命名需遵循 UTF-8 格式,避免特殊字符,长度不超过 64 字节,且部分名称如 `admin`、`local` 和 `config` 为系统保留。删除数据库可通过 `db.dropDatabase()` 实现,主要用于移除已持久化的数据库。
624 0
|
存储 JSON NoSQL
MongoDB常用命令
MongoDB常用命令
117 1
MongoDB常用命令
|
NoSQL MongoDB 数据库
MongoDB是一个NoSQL数据库,有着多种不同的命令和操作。以下是一些常见的MongoDB命令:
一些常用的MongoDB命令,如数据库和集合的管理、数据的插入、查询、更新、删除以及聚合操作等。
186 1
|
SQL NoSQL 安全
MongoDB命令汇总
这篇文章提供了一个MongoDB命令的汇总,包括数据库操作、DDL和DML命令、安全管理、数据备份恢复、远程连接管理和聚合操作等。
594 2

推荐镜像

更多