mongodb之用戶管理與系統管理經常使用命令

## mongodb的用戶管理(認證管理)redis

  • 用戶分三種    mongodb

       全局用戶
shell

         數據庫對應用戶
數據庫

         只讀用戶
app


### 建立全局用戶(全局用戶只能在admin帳戶下建立)ide

  • 建立了一個名爲zhuima,密碼爲zhuima的全局帳戶ui


[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選項this

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


### 重啓mongodb進行驗證 這裏能夠看到咱們進行show的時候提示沒權限lua

[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便可
spa

### 想要切換到全局用戶時,必須先要進入admin數據庫才能夠

[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
>


### 建立對應數據庫的用戶

> 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這個數據庫進行權限操做

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


### 增長一個只讀用戶

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


### 刪除一個用戶

> 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,你會發現原來世界那麼美好

> 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
>

### 查看當前所在數據庫位置

  • 第一種方式

> 
> db.status
admin.status
>
  • 第二種方式

> db.getName();
admin
>


### 當前數據庫版本

> db.version()
2.6.3
>


### 查看當前數據庫中的包含的集合

> show collections
system.indexes
system.users
system.version


### 刪除數據庫

  • 切換到該數據庫目錄下,進行drop操做便可

> 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的狀態

> 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數據的大小

> db.system.users.dataSize()
720
>


### 增刪查改的文章請移步到上篇文章

相關文章
相關標籤/搜索