MongoDB数据库用户名和密码的设置

今天开始做MongoDB的学习总结,感觉MongoDB的也不是想象中那么难,不过如果熟悉javascript的话,学习MongoDB就更容易上手。

首先是对MongoDB用户和权限的设置,如果不设置用户的话,直接使用mongo命令就可以进入客户端shell界面进行操作了,但是如果没有设置用户的话,总感觉少了点什么,于是经过半天的查找和实践,差不多把用户和权限弄明白了。总结如下:

如果按照以下这个指令安装的话:
mongod --install --dbpath "C:\Program Files\mongodb\data\db" --logpath "C:\Program Files\mongodb\data\log\MongoDB.log"

如下:
c:\Program Files\mongodb\bin>mongod --install --dbpath "C:\Program Files\mongodb\data\db" --logpath "C:\Program Files\mongodb\data\log\MongoDB.log"
Fri Apr 05 13:47:43.164
Fri Apr 05 13:47:43.168 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Fri Apr 05 13:47:43.169
Fri Apr 05 13:47:43.169 Trying to install Windows service 'MongoDB'
Fri Apr 05 13:47:43.170 There is already a service named 'MongoDB', aborting
c:\Program Files\mongodb\bin>net start MongoDB
Mongo DB 服服务务已已经经启启动动成成功功。。
c:\Program Files\mongodb\bin>mongo
MongoDB shell version: 2.4.1
connecting to: test
Server has startup warnings:
Fri Apr 05 13:48:02.516 [initandlisten]
Fri Apr 05 13:48:02.516 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
Fri Apr 05 13:48:02.516 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).
Fri Apr 05 13:48:02.516 [initandlisten] **       Note that journaling defaults to off for 32 bit and is currently off.
Fri Apr 05 13:48:02.516 [initandlisten] **       See http://dochub.mongodb.org/core/32bit
Fri Apr 05 13:48:02.516 [initandlisten]
show dbs
admin   (empty)
local   0.03125GB
>
可以看到有两个默认的数据库admin和local
实例1:创建一个用户名为root,密码为admin的用户,如下:
> use admin
switched to db admin
db.addUser("root","admin")
{
        "user" : "root",
        "readOnly" : false,
        "pwd" : "bde0d84f6749c235a6b4e36d945eb666",
        "_id" : ObjectId("515e662430d89f61f6991c91")
}
show collections
Fri Apr 05 13:50:36.685 JavaScript execution failed: error: {
        "$err" : "not authorized for query on admin.system.namespaces",
        "code" : 16550
} at src/mongo/shell/query.js:L128
>
说明:使用以上指令show collections的时候,发现报错了。是因为没有权限。做如下操作:
db.auth("root","admin");
1
说明:返回1表示验证成功了,返回0表示验证失败。
此时,输入以下指令:show collections则可以看到admin下的集合了。
> show collections
system.indexes
system.users
> db.system.users.find()
{ "_id" : ObjectId("515e662430d89f61f6991c91"), "user" : "root", "readOnly" : false, "pwd" : "bde0d84f6749c235a6b4e36d945eb666" }
>
实例2:在用户名为root,密码为admin的用户下创建一个student数据库并在student数据库中创建一个stu的集合并插入一个文档,如下:
use student
switched to db student
db.stu.insert({"name":"maoyuanjun","age":25,"sex":"male"})
db.stu.find()
{ "_id" : ObjectId("515e676630d89f61f6991c92"), "name" : "maoyuanjun", "age" : 25, "sex" : "male" }
退出服务器,重新登陆如下:
c:\Program Files\mongodb\bin>mongo
MongoDB shell version: 2.4.1
connecting to: test
> show dbs
Fri Apr 05 13:58:05.420 JavaScript execution failed: listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" 
at src/mongo/shell/mongo.js:L46
出错原因:是没有权限。则先判断是否有权限,如下:
> use admin
switched to db admin
> db.auth("root","admin")
1
> show dbs
admin   0.0625GB
local   0.03125GB
student 0.0625GB
>
这时,我们可以看到用户root,密码admin的用户下多了一个student数据库。
实例3:在创建一个用户
c:\Program Files\mongodb\bin>mongo
MongoDB shell version: 2.4.1
connecting to: test
> use admin
switched to db admin
直接添加用户会报错:
> db.addUser("test","123456")
Fri Apr 05 14:01:31.404 JavaScript execution failed: error: { "$err" : "not authorized for query on admin.system.users", "code" : 16550 } at src/mongo/shell/query.js:L128
做权限的判断:
> db.auth("root","admin");
1
> use admin
switched to db admin
> db.addUser("test",123456)
{
        "user" : "test",
        "readOnly" : false,
        "pwd" : "c8ef9e7ab00406e84cfa807ec082f59e",
        "_id" : ObjectId("515e68e2be252e81c5dee198")
}
> show collections
system.indexes
system.users
> db.system.users.find()
{ "_id" : ObjectId("515e662430d89f61f6991c91"), "user" : "root", "readOnly" : fa
lse, "pwd" : "bde0d84f6749c235a6b4e36d945eb666" }
{ "_id" : ObjectId("515e68e2be252e81c5dee198"), "user" : "test", "readOnly" : fa
lse, "pwd" : "c8ef9e7ab00406e84cfa807ec082f59e" }
>
可以看到已经有两个账户了。
以上创建好用户之后,就可以使用java代码来判断连接是否成功了:
package com.MongoDBDemo;


import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/*
 * MongoDB的连接和关闭
 */
public class MongoDBUtil {
	public static void main(String[] args) {
		Mongo m = null;
		DB db = null;
		try {
			//Mongo(param1, param2):param1为IP地址    param2为端口
			m = new Mongo("127.0.0.1", 27017);
			//根据mongodb数据库的名称获取mongodb对象
			db = m.getDB("admin");
			//校验用户密码是否正确  
            if (!db.authenticate("root", "admin".toCharArray())){  
                System.out.println("连接MongoDB数据库,校验失败!");  
            }else{ 
            	System.out.println("连接MongoDB数据库,校验成功!");  
            }
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}finally{//mongodb连接关闭
			try{
				m.close();
			} catch(Exception ee) {
				ee.printStackTrace();
			}
			m = null;
		}
	}
}

阅读更多
个人分类: MongoDB
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭