一. 下载地址:http://www.MongoDB.org/downloads
二.位置
软件安装位置:/apps/svr/mongodb
数据存放位置:/data/mongodb/db
日志存放位置:/data/mongodb/logs
三.检查是否安装过mongodb
rpm -qa | grep mongodb
service mongodb status
四.安装
[root@localhost /]# cd /apps/svr/
[root@localhost /]# groupadd mongodb
[root@localhost /]# useradd mongodb -g mongodb
[root@localhost /]# cd /apps/svr
[root@localhost local]# tar -zxv -f mongodb-Linux-x86_64-2.2.2.tgz
[root@localhost local]# mv mongodb-linux-x86_64-2.2.2 mongodb
[root@localhost local]# chown -R mongodb: mongodb mongodb
[root@localhost local]# cd mongodb
[root@localhost mongodb]# mkdir -p /data/mongodb/db
[root@localhost mongodb]# mkdir /data/mongodb/logs
[root@localhost mongodb]# vi /etc/sysconfig/iptables // 将27017端口加入防火墙
[root@localhost mongodb]# service iptables restart // 重启防火墙
MongoDB设置为系统服务并且设置开机启动
a 通过上面简单的操作,我们已经将MongoDB配置文件配置完成,那么接下里我们将为MongoDB设置系统服务。
b.首先添加MongoDB系统服务,命令如下:vim /etc/rc.d/init.d/mongod
c 打开编辑器后,我们将下面的配置粘贴进去,然后保存
d 保存完成之后,添加脚本执行权限,命令如下:chmod +x /etc/rc.d/init.d/mongod
e 启动MongoDB,如下图所示,则说明启动成功
f 可以使用命令service mongod stop关闭MongoDB服务。
g 将此服务设置为开机启动,命令如下:chkconfig mongod on,然后重新启动机器进行测试,发现开机服务应启动并且端口也在使用中。
h 验证mongoDB是否启动,输入命令lsof -i :27017,监测端口已经在使用中,所以说启动已经完成。
配置mongodb.conf 文件
dbpath=/data/mongodb/db
logpath=/data/mongodb/logs/mongodb.log
port=27017
fork=true
nohttpinterface=true
*************************************************************************************
启动mongodb
1. sevice mongod start 启动服务器
2.启动命令
./mongo
MongoDB shell version v3.4.2connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Server has startup warnings:
2017-04-07T13:43:58.846+0800 I STORAGE [initandlisten]
2017-04-07T13:43:58.846+0800 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-04-07T13:43:58.846+0800 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
> show dbs;
admin 0.000GB
local 0.000GB
> show dbs
admin 0.000GB
local 0.000GB
/
和其他所有数据库一样,权限的管理都差不多一样。mongodb存储所有的用户信息在admin 数据库的集合system.users中,保存用户名、密码和数据库信息。mongodb默认不启用授权认证,只要能连接到该服务器,就可连接到mongod。若要启用安全认证,需要更改配置文件参数auth。
1.查看数据库:
> show dbs
发现 admin 竟然没有!~
直接创建用户admin
use admin
db.createUser(
{
user: "admin",
pwd: "admin",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
成功创建,再查询admin中的集合,有数据了!
> show collections
system.users
system.version
查看 集合的信息:
> db.system.users.find();
{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "cFISfpbm04pmIFpqiL340g==", "storedKey" : "WG1DSEEEHUZUBjsjsnEA4RFVY2M=", "serverKey" : "9Lm+IX6l9kfaE/4C25/ghsQpDkE=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
>
> db.system.version.find();
{ "_id" : "authSchema", "currentVersion" : 5 }
>
现在启用 auth:
[root@localhost ~]# vim /etc/mongod.conf
auth=true
重启 mongod 服务:
[root@localhost ~]# service mongod restart
直接默认登录,查看集合,发现无权操作了:
[root@localhost ~]# ./mongoMongoDB shell version: 3.0.2
connecting to: test
> show dbs
2015-05-09T21:57:03.176-0700 E QUERY Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13
}
at Error (<anonymous>)
at Mongo.getDBs (src/mongo/shell/mongo.js:47:15)
at shellHelper.show (src/mongo/shell/utils.js:630:33)
at shellHelper (src/mongo/shell/utils.js:524:36)
at (shellhelp2):1:1 at src/mongo/shell/mongo.js:47
>
刚才在数据库 admin 创建了一个账户 admin ,先到数据admin进来连接(其他db则失败):
[root@localhost ~]# ./mongo
MongoDB shell version: 3.0.2
connecting to: test
>
> db.auth("admin","admin")
Error: 18 Authentication failed.
0
> use mydata
switched to db mydata
> db.auth("admin","admin")
Error: 18 Authentication failed.
0
> use admin
switched to db admin
> db.auth("admin","admin")
1
>
db.auth("admin","admin") 返回值为1,说明登录成功!~db.auth("admin","admin") 记录是不存在的,执行完后这一行在shell中不会记录历史。
所以现在创建另一个用户"myuser"
db.createUser(
{
user: "myuser",
pwd: "myuser",
roles: [ { role: "readWrite", db: "mydata" } ]
}
)
也可以增删角色:
#授予角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ])
db.grantRolesToUser( "myuser" , [ { role: "dbOwner", db: "mydb" } ])
#取消角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ])
db.revokeRolesFromUser( "myuser" , [ { role: "readWrite", db: "mydb" } ])
因为在admin数据库创建的,只能在 admin 数据库中登录:
> db.auth("myuser","myuser")
Error: 18 Authentication failed.
0
>
> db
mydb
> use admin
switched to db admin
> db.auth("myuser","myuser");
1
>
此时是可以切换到所在的数据库进行相关操作:
> use mydb
switched to db mydb
>
> db.tab.save({"id":999});
WriteResult({ "nInserted" : 1 })
>
> db.tab.find({"id":999});
{ "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }
>
> show collections
system.indexes
tab
>
在创建用户时可以在其数据库中创建,这样不用每次都进入admin数据库登录后再切换。如在数据库"mydb"创建用户"userkk"。
use admin
db.auth("admin","admin")
use mydb
db.createUser(
{
user: "userkk",
pwd: "userkk",
roles: [ { role: "dbOwner", db: "mydb" } ]
}
)
db.auth("userkk","userkk")
------------------------------------------------------------------------------------------------------------------
华丽分割
------------------------------------------------------------------------------------------------------------------
现在授权测试:
#先访问到admin数据库
- use admin
- db.auth("admin","admin")
#roles: 创建角色"testRole"在数据库 "mydb" 中
#privileges: 该角色可查看"find"数据库"mydb"的所有集合
#db.dropRole("testRole")
- use mydb
- db.createRole({
- role: "testRole",
- privileges: [{ resource: { db: "mydb", collection: "" }, actions: [ "find" ] }],
- roles: []
- })
#在admin数据库生成集合system.roles。查看角色。
- > use admin
- switched to db admin
- >
- > show collections
- system.indexes
- system.roles
- system.users
- system.version
- >
- > db.system.roles.find();
- { "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find" ] } ], "roles" : [ ] }
- >
#回到mydb,在数据库mydb中创建用户并授予角色"testRole"
#db.dropUser("userkk")
- use mydb
- db.createUser(
- {
- user: "userkk",
- pwd: "userkk",
- roles: [ { role: "testRole", db: "mydb" } ]
- }
- )
退出mongodb,重新登录进行操作。发现只能使用find
>exit
- [root@localhost ~]# mongo
- MongoDB shell version: 3.0.2
- connecting to: test
- > use mydb
- switched to db mydb
- >
- > db.auth("userkk","userkk")
- 1
- >
- > db.tab.find({"id":999})
- { "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }
- >
- > db.tab.insert({"id":1000})
- WriteResult({
- "writeError" : {
- "code" : 13,
- "errmsg" : "not authorized on mydb to execute command { insert: \"tab\", documents: [ { _id: ObjectId('554f145cdf782b42499d80e5'), id: 1000.0 } ], ordered: true }"
- }
- })
- >
给角色 "testRole" 添加3个 “Privileges”权限: "update", "insert", "remove"。再重新操作。
- use admin
- db.auth("admin","admin")
- use mydb
- #添加Privileges给角色
- db.grantPrivilegesToRole("testRole",
- [{ resource: { db: "mydb", collection: "" },actions: [ "update", "insert", "remove" ]}
- ])
- exit #退出mongodb重新登录
- use mydb
- db.auth("userkk","userkk")
- #增删数据可以操作了!~
- db.tab.insert({"id":1000})
- db.tab.find({"id":1000})
- db.tab.remove({"id":1000})
- #此时admin的角色记录为:
- > db.system.roles.find();
- { "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find", "insert", "remove", "update" ] } ], "roles" : [ ] }
- >
#更改角色 roles,把roles值全部更新。同样Privileges也可以更新替换!~
- use admin
- db.auth("admin","admin")
- use mydb
- db.updateRole("testRole",{ roles:[{ role: "readWrite",db: "mydb"}]},{ w:"majority" })
- db.auth("userkk","userkk")
- show dbs
--mongodb修改用户名密码:
利用db.changeUserPassword
- > db.changeUserPassword('username','password');
db.changeUserPassword('readuser','aaa');
关于角色,参考官方文档提取总结如下:
角色分类 | 角色 | 权限及角色 (本文大小写可能有些变化,使用时请参考官方文档) |
Database User Roles | read | CollStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections |
readWrite | CollStats,ConvertToCapped,CreateCollection,DbHash,DbStats, DropCollection,CreateIndex,DropIndex,Emptycapped,Find, Insert,KillCursors,ListIndexes,ListCollections,Remove, RenameCollectionSameDB,update | |
Database Administration Roles | dbAdmin | collStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections, dropCollection 和 createCollection 在 system.profile |
dbOwner | 角色:readWrite, dbAdmin,userAdmin | |
userAdmin | ChangeCustomData,ChangePassword,CreateRole,CreateUser, DropRole,DropUser,GrantRole,RevokeRole,ViewRole,viewUser | |
Cluster Administration Roles | clusterAdmin | 角色:clusterManager, clusterMonitor, hostManager |
clusterManager | AddShard,ApplicationMessage,CleanupOrphaned,FlushRouterConfig, ListShards,RemoveShard,ReplSetConfigure,ReplSetGetStatus, ReplSetStateChange,Resync,
EnableSharding,MoveChunk,SplitChunk,splitVector | |
clusterMonitor | connPoolStats,cursorInfo,getCmdLineOpts,getLog,getParameter, getShardMap,hostInfo,inprog,listDatabases,listShards,netstat, replSetGetStatus,serverStatus,shardingState,top
collStats,dbStats,getShardVersion | |
hostManager | applicationMessage,closeAllDatabases,connPoolSync,cpuProfiler, diagLogging,flushRouterConfig,fsync,invalidateUserCache,killop, logRotate,resync,setParameter,shutdown,touch,unlock | |
Backup and Restoration Roles | backup | 提供在admin数据库mms.backup文档中insert,update权限 列出所有数据库:listDatabases 列出所有集合索引:listIndexes
对以下提供查询操作:find *非系统集合 *系统集合:system.indexes, system.namespaces, system.js *集合:admin.system.users 和 admin.system.roles |
restore | 非系统集合、system.js,admin.system.users 和 admin.system.roles 及2.6 版本的system.users提供以下权限: collMod,createCollection,createIndex,dropCollection,insert
列出所有数据库:listDatabases system.users :find,remove,update | |
All-Database Roles | readAnyDatabase | 提供所有数据库中只读权限:read 列出集群所有数据库:listDatabases |
readWriteAnyDatabase | 提供所有数据库读写权限:readWrite 列出集群所有数据库:listDatabases | |
userAdminAnyDatabase | 提供所有用户数据管理权限:userAdmin Cluster:authSchemaUpgrade,invalidateUserCache,listDatabases admin.system.users和admin.system.roles: collStats,dbHash,dbStats,find,killCursors,planCacheRead createIndex,dropIndex | |
dbAdminAnyDatabase | 提供所有数据库管理员权限:dbAdmin 列出集群所有数据库:listDatabases | |
Superuser Roles | root | 角色:dbOwner,userAdmin,userAdminAnyDatabase readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase,clusterAdmin |
Internal Role | __system | 集群中对任何数据库采取任何操作 |
命令应用:
http://www.cnblogs.com/eggTwo/p/4040580.html
------------------------------------------------------------------------------------------------------------------
华丽分割
------------------------------------------------------------------------------------------------------------------
现在授权测试:
#先访问到admin数据库
- use admin
- db.auth("admin","admin")
#roles: 创建角色"testRole"在数据库 "mydb" 中
#privileges: 该角色可查看"find"数据库"mydb"的所有集合
#db.dropRole("testRole")
- use mydb
- db.createRole({
- role: "testRole",
- privileges: [{ resource: { db: "mydb", collection: "" }, actions: [ "find" ] }],
- roles: []
- })
#在admin数据库生成集合system.roles。查看角色。
- > use admin
- switched to db admin
- >
- > show collections
- system.indexes
- system.roles
- system.users
- system.version
- >
- > db.system.roles.find();
- { "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find" ] } ], "roles" : [ ] }
- >
#回到mydb,在数据库mydb中创建用户并授予角色"testRole"
#db.dropUser("userkk")
- use mydb
- db.createUser(
- {
- user: "userkk",
- pwd: "userkk",
- roles: [ { role: "testRole", db: "mydb" } ]
- }
- )
退出mongodb,重新登录进行操作。发现只能使用find
>exit
- [root@localhost ~]# mongo
- MongoDB shell version: 3.0.2
- connecting to: test
- > use mydb
- switched to db mydb
- >
- > db.auth("userkk","userkk")
- 1
- >
- > db.tab.find({"id":999})
- { "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }
- >
- > db.tab.insert({"id":1000})
- WriteResult({
- "writeError" : {
- "code" : 13,
- "errmsg" : "not authorized on mydb to execute command { insert: \"tab\", documents: [ { _id: ObjectId('554f145cdf782b42499d80e5'), id: 1000.0 } ], ordered: true }"
- }
- })
- >
给角色 "testRole" 添加3个 “Privileges”权限: "update", "insert", "remove"。再重新操作。
- use admin
- db.auth("admin","admin")
- use mydb
- #添加Privileges给角色
- db.grantPrivilegesToRole("testRole",
- [{ resource: { db: "mydb", collection: "" },actions: [ "update", "insert", "remove" ]}
- ])
- exit #退出mongodb重新登录
- use mydb
- db.auth("userkk","userkk")
- #增删数据可以操作了!~
- db.tab.insert({"id":1000})
- db.tab.find({"id":1000})
- db.tab.remove({"id":1000})
- #此时admin的角色记录为:
- > db.system.roles.find();
- { "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find", "insert", "remove", "update" ] } ], "roles" : [ ] }
- >
#更改角色 roles,把roles值全部更新。同样Privileges也可以更新替换!~
- use admin
- db.auth("admin","admin")
- use mydb
- db.updateRole("testRole",{ roles:[{ role: "readWrite",db: "mydb"}]},{ w:"majority" })
- db.auth("userkk","userkk")
- show dbs
--mongodb修改用户名密码:
利用db.changeUserPassword
- > db.changeUserPassword('username','password');
db.changeUserPassword('readuser','aaa');
关于角色,参考官方文档提取总结如下:
角色分类 | 角色 | 权限及角色 (本文大小写可能有些变化,使用时请参考官方文档) |
Database User Roles | read | CollStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections |
readWrite | CollStats,ConvertToCapped,CreateCollection,DbHash,DbStats, DropCollection,CreateIndex,DropIndex,Emptycapped,Find, Insert,KillCursors,ListIndexes,ListCollections,Remove, RenameCollectionSameDB,update | |
Database Administration Roles | dbAdmin | collStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections, dropCollection 和 createCollection 在 system.profile |
dbOwner | 角色:readWrite, dbAdmin,userAdmin | |
userAdmin | ChangeCustomData,ChangePassword,CreateRole,CreateUser, DropRole,DropUser,GrantRole,RevokeRole,ViewRole,viewUser | |
Cluster Administration Roles | clusterAdmin | 角色:clusterManager, clusterMonitor, hostManager |
clusterManager | AddShard,ApplicationMessage,CleanupOrphaned,FlushRouterConfig, ListShards,RemoveShard,ReplSetConfigure,ReplSetGetStatus, ReplSetStateChange,Resync,
EnableSharding,MoveChunk,SplitChunk,splitVector | |
clusterMonitor | connPoolStats,cursorInfo,getCmdLineOpts,getLog,getParameter, getShardMap,hostInfo,inprog,listDatabases,listShards,netstat, replSetGetStatus,serverStatus,shardingState,top
collStats,dbStats,getShardVersion | |
hostManager | applicationMessage,closeAllDatabases,connPoolSync,cpuProfiler, diagLogging,flushRouterConfig,fsync,invalidateUserCache,killop, logRotate,resync,setParameter,shutdown,touch,unlock | |
Backup and Restoration Roles | backup | 提供在admin数据库mms.backup文档中insert,update权限 列出所有数据库:listDatabases 列出所有集合索引:listIndexes
对以下提供查询操作:find *非系统集合 *系统集合:system.indexes, system.namespaces, system.js *集合:admin.system.users 和 admin.system.roles |
restore | 非系统集合、system.js,admin.system.users 和 admin.system.roles 及2.6 版本的system.users提供以下权限: collMod,createCollection,createIndex,dropCollection,insert
列出所有数据库:listDatabases system.users :find,remove,update | |
All-Database Roles | readAnyDatabase | 提供所有数据库中只读权限:read 列出集群所有数据库:listDatabases |
readWriteAnyDatabase | 提供所有数据库读写权限:readWrite 列出集群所有数据库:listDatabases | |
userAdminAnyDatabase | 提供所有用户数据管理权限:userAdmin Cluster:authSchemaUpgrade,invalidateUserCache,listDatabases admin.system.users和admin.system.roles: collStats,dbHash,dbStats,find,killCursors,planCacheRead createIndex,dropIndex | |
dbAdminAnyDatabase | 提供所有数据库管理员权限:dbAdmin 列出集群所有数据库:listDatabases | |
Superuser Roles | root | 角色:dbOwner,userAdmin,userAdminAnyDatabase readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase,clusterAdmin |
Internal Role | __system | 集群中对任何数据库采取任何操作 |