一、基礎語句
1.創建數據庫並查看當前數據庫
> use wang
> db
2.查看數據庫的版本
> db.version()
3.刪除數據庫
> use wang
> db.dropDatabase()
4.插入文檔
> db.test.insert({ id : 1 , "name " : "wangchongyang" ,"age" : 19, " hobby":" read "})
5.更新文檔
> db.test.update({id:1},{$set:{ id : 11}})
6.刪除文檔
> db.test.remove({ id : 11})
7.查詢文檔
> db.test.find()
> db.test.findOne()
> db.test.find({ id : 11})
8.文檔排序
> db.test.find().sort().sort({ "id" : 1}) 1 升序,-1 降序
9.創建索引
> db.test.ensureIndex({ id : 1 }) 1 按升序創建索引 -1降序
10.刪除索引
> db.test.dropIndex( id )
11.聚合
> db.test.aggregate({ $group : { _id: "name",num : { $num : 1 }} })
12.備份與恢復
mongodump -h 127.0.0.1:27017 -d test -o /tmp/mongo_backup
mongorestore -d test /tmp/mongo_backup/*
13.去掉重複數據
> db.test.distinct( ' name' )
二、集合語句指導
1.查看集合幫助
db.test.help()
2.查看集合總數量
db.test.count()
3.查看錶空間大小
db.test.dataSize()
4.查看集合所在的數據庫
db.test.getDB()
5.查看當前集合狀態
db.test.stats()
6. 集合重命名
db.test.renameCollection("testdb")
7.刪除集合
db.testdb.drop()
8. 查看當前數據庫所有集合
db.getCollectionNames()
9. 查看所有集合的狀態
db.printCollectionStats();
10.現有表以及數據添加字段
db.test.update({}, {$set:{nFlagState:0}}, false, true);
11.查看當前連接數
db.serverStatus().connections
三、複製以及分片語句
1. 配置mongodb 集羣中一個Replica Sets模式的shard,並初始化
config = {_id: 'shard4', members: [
{_id: 0, host: '10.181.49.224:27001'},
{_id: 1, host: '10.181.49.221:27002'},
{_id: 2, host: '10.181.49.222:27003'}]
}
rs.initiate(config)
2. 將一個shard 加入到集羣中
db.runCommand({addshard:"shard4/10.181.49.224:27001,10.181.49.221:27002,10.181.49.224:27002",name:"shard2"})
3. 查看shard 信息
db.runCommand({listshards:1})
4. 將一個庫使用shard
db.runCommand({ enablesharding:"okooo" })
5. 查看replica set 的狀態
rs.status()
state字段說明
0 | Starting up, phase 1 |
1 | Primary |
2 | Secondary |
3 | Recovering |
4 | Fatal error |
5 | Starting up, phase 2 |
6 | Unknown state |
7 | Arbiter |
8 | Down |
heath字段說明
0 | Server is down |
1 | Server is up |
6. 查看replica set 中是否是主節點
rs.isMaster()
7.查看當前數據庫的數據同步狀態
db.printReplicationInfo()
8. 查看整個shard的同步狀態
db.printSlaveReplicationInfo()
9. 當前運行的進程
db.currentOp();
10. 看數據庫信息
db.stats()
11. 看數據實例信息
db.serverStatus()
12. (在主庫上執行)增加一個從庫
rs.add("192.168.8.226:27004")
13. (在主庫上執行)減少一個從庫
rs.remove("192.168.8.226:27004")
14. 看錶的狀態
db.users.stats()
15. 看shard 狀態
db.printShardingStatus()
db.printShardingStatus( true )
16. 對已有的表進行shard
db.runCommand({ shardcollection: "test.users_2", key: { _id:1 }}) --users_2表根據_id 鍵分區
17. 移除一個shard
db.runCommand({"removeshard" : "localhost:20002"});
18. 從庫支持查詢
db.getMongo().setSlaveOk()
19. 查看慢查詢
db.system.profile.find()
20. 打開profile
打開profile有兩種
一種直接在啓動參數裏直接設置,啓動 MongoDB時加上 --profile=級別即可。
另一種就是客服端調用後db.setProfilingLevel(級別,秒數) ,但是這隻影響本次會話。
21.啓用分片
db.adminCommand({"enableSharding" : "blog"}) 在blog 庫上建立sharding
22.在blog庫上的posts表上利用date和author兩個字段建立sharding
db.adminCommand({"shardCollection" : "blog.posts", key : {"date" : 1, "author" : 1}}
四、用戶管理
MongoDB 默認的啓動是不驗證用戶名和密碼的,啓動MongoDB 後,可以直接用MongoDB 連接上來,對所有的庫具有root 權限。所以啓動的時候指定參數,可以阻止客戶端的訪問和連接。
先啓用系統的登錄驗證模塊, 只需在啓動時指定 auth 參數即可,如:
[root@template ~]# mongod --auth
[root@template ~]# mongo
MongoDB shell version: 2.6.0
connecting to: test
>
在最初始的時候 MongoDB 都默認有一個 admin 數據庫(默認是空的),而 admin.system.users 中將會保存比在其它數據庫中設置的用戶權限更大的用戶信息。
注意:當 admin.system.users 中沒有添加任何用戶時,即使 MongoDB 啓動時添加了 --auth參數,如果在除 admin 數據庫中添加了用戶,此時不進行任何認證依然可以使用任何操作,直到知道你在 admin.system.users 中添加了一個用戶。
1.建立系統root用戶
> show dbs
admin (empty)
local 0.078GB
> use admin
switched to db admin
> db.createUser({user:"gyw",pwd:"123456",roles:[{role:"root",db:"admin"}]})
Successfully added user: {
"user" : "gyw",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
> show dbs
2016-07-29T09:19:32.668+0800 listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13
} at src/mongo/shell/mongo.js:47
提示沒有權限失敗
重新以認證的方式登錄數據庫
mongo --port 27017 -u gyw -p 123456 --authenticationDatabase admin
MongoDB shell version: 2.6.0
connecting to: 127.0.0.1:27017/test
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : "admin.gyw", "user" : "gyw", "db" : "admin", "credentials" : { "MONGODB-CR" : "871b1cf91cd1ebb7acf0f4040af47979" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
2.創建單庫最大權限用戶
> use test
switched to db test
> db.test.insert({id:1,name:"mi"})
WriteResult({ "nInserted" : 1 })
> db.createUser({user:"wjb",pwd:"123456",roles:[{role:"dbOwner",db:"test"}]})
Successfully added user: {
"user" : "wjb",
"roles" : [
{
"role" : "dbOwner",
"db" : "test"
}
]
}
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : "admin.gyw", "user" : "gyw", "db" : "admin", "credentials" : { "MONGODB-CR" : "871b1cf91cd1ebb7acf0f4040af47979" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.wjb", "user" : "wjb", "db" : "test", "credentials" : { "MONGODB-CR" : "3ec31d8a58e61f450c5988b546dfde4b" }, "roles" : [ { "role" : "dbOwner", "db" : "test" } ] }
我們無權限認證登錄看能否訪問test數據庫
[root@template 27017]# mongo --port 27017
MongoDB shell version: 2.6.0
connecting to: 127.0.0.1:27017/test
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
> use test
switched to db test
> show collections
2016-07-29T09:26:17.440+0800 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
可以發現提示我們沒有權限
通過權限認證登錄
[root@template 27017]# mongo --port 27017 -u wjb -p 123456 --authenticationDatabase test
MongoDB shell version: 2.6.0
connecting to: 127.0.0.1:27017/test
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
> use test
switched to db test
> show collections
system.indexes
test
下方列出系統內置角色名稱:
Database User Roles 普通用戶角色
read
readWrite
Database Administration Roles 管理員角色
dbAdmin 可以管理數據庫
dbOwner 單數據庫最大權限,dbAdmin,userAdmin
userAdmin 可管理當前數據庫用戶
Cluster Administration Roles 管理員角色
clusterAdmin
clusterManager
clusterMonitor
hostManager
Backup and Restoration Roles 備份和恢復角色
backup
restore
All-Database Roles 所有數據庫角色
readAnyDatabase 在admin下建立,可以讀取所有數據庫的信息
readWriteAnyDatabase 在admin下建立,可以讀寫所有數據庫的信息
userAdminAnyDatabase 在admin下建立,可以管理所有數據庫的用戶
dbAdminAnyDatabase 在admin下建立,可以管理所有數據庫的信息(類似於所有數據庫的dbAdmin賬戶)
Superuser Roles ()
root