1. Start MongoDB in the form of a command
2. Create user assignment permissions
2.1. Open a new cmd window and enter the MongoDB installation directory, under the bin file; execute the following command
Mongo
As shown
2.2. Add an administrative user (mongoDB has no invincible user root, only userAdminAnyDatabase who can manage users) The following command creates an account for adding a user: admin password; 123456
Execute the following two commands in the cmd command window:
use admin
db.createUser( {user:"admin",pwd: "123456",roles: [ { role:"userAdminAnyDatabase", db: "admin" } ]})
As shown below
Note: After adding users, you can use the show users command to view existing users
As shown below
2.3. After adding the management user, close MongoDB , and use the permission method to open MongoDB again . Be careful not to use kill to kill the mongodb process directly. (If you do, please delete the mongo.lock file in the data/db directory) .
Execute the following command to shut down the mongo database service
db.shutdownServer()
View the Mongo database service shutdown results in the first opened cmd command window . As shown below
If the Mongo service is successfully shut down, execute the following command to open MongoDB again with permission ;
mongod--dbpath E:/mongodb/data --port 57147 --logpath E:/mongodb/log/log.log --bind_ip 127.0.0.1 –auth
Parameter Description:
--port specifies the port, the default is 27017 , use 57147 here
--dbpath data directory path
--logpath log file path
--auth 开启安全验证
--bind_ip 指定监听的ip;允许访问IP地址
2.4、创建读写用户
在客户端命令执行的cmd窗口中执行以下六条命令:
mongo 127.0.0.1:27017
use license
use admin
db.auth("admin","123456")
db.getSiblingDB("license").runCommand({authSchemaUpgrade:1})
db.createUser({user:"license",pwd:"123456",roles:[{role:"readWrite",db:"license"}]})
成功标识
以上全部命令执行成功后,创建了一个数据库为license的实例,且登录账号为license,密码123456。
3、JAVA连接测试
Mongo mongo = new Mongo("127.0.0.1", "27017");
DB db = mongo.getDB("dbname");
boolean auth = db.authenticate("name","password".toCharArray());
验证成功则返回true 否则返回false
注:db验证只能一次,如果成功后就不能继续验证,否则会报重复验证异常
4、MongoDB自动备份
编写一个bat文件,文件内容如下:
@ECHO OFF
if not exist E:\mongodb\data\dbbak\%date:~0,4%\%date:~5,2%\%date:~8,2%\ md E:\mongodb\data\dbbak\%date:~0,4%\%date:~5,2%\%date:~8,2%\
cd E:\mongodb\bin
E:mongodump -h 127.0.0.1:57147 -d license -ulicense -p 123456 --authenticationDatabase admin -oE:\mongodb\data\dbbak\%date:~0,4%\%date:~5,2%\%date:~8,2%\
if exist E:\mongodb\data\dbbak\%date:~0,4%\%date:~5,2%\%date:~8,2%\md E:\mongodb\data\dbbak\%date:~0,4%\%date:~5,2%\%date:~8,2%\
将上面的bat文件添加到windows的计划任务内,即可完成自动备份