search
HomeDatabaseMysql Tutorialmongodb 用户 权限 设置 详解

mongodb 用户 权限 设置 详解

Jun 07, 2016 pm 04:32 PM
mongodbRelationaldatabasePermissionsuserKnowset upDetailed explanation

我知道的关系型数据库都是有权限控制的,什么用户能访问什么库,什么表,什么用户可以插入,更新,而有的用户只有读取权限。 例如:mysql安装配置好后,有一个自带的mysql数据库,里面有一张user表,用来存放用户,以及用户权限,而mongodb这个最像关系型的

我知道的关系型数据库都是有权限控制的,什么用户能访问什么库,什么表,什么用户可以插入,更新,而有的用户只有读取权限。

例如:mysql安装配置好后,有一个自带的mysql数据库,里面有一张user表,用来存放用户,以及用户权限,而mongodb这个最像关系型的数据库,有没有这样的表呢。

一,掌握权限,理解下面4条基本上就差不多

1,mongodb是没有默认管理员账号,所以要先添加管理员账号,在开启权限认证。

2,切换到admin数据库,添加的账号才是管理员账号。

3,用户只能在用户所在数据库登录,包括管理员账号。

4,管理员可以管理所有数据库,但是不能直接管理其他数据库,要先在admin数据库认证后才可以。这一点比较怪

二,添加管理员账号

[root@localhost zhangy]# mongo
MongoDB shell version: 2.4.6
connecting to: tank
> use admin                    //切换到admin数据库
switched to db admin
> show collections;
system.indexes
system.users                   //用户表
> db.system.users.find();      //用户表没有数据
> db.addUser('tank','test');   //添加一个管理员账号
{
    "user" : "tank",
    "readOnly" : false,
    "pwd" : "988432606980d0695e4f668f6bbc643a",
    "_id" : ObjectId("529e5d543b6a4608ac833429")
}

三,开启动用户权限认证

[root@localhost zhangy]# vim /etc/mongodb.conf           //将auth=true前面的注释拿掉
[root@localhost zhangy]# /etc/init.d/mongod restart      //重启生效

四,用户只能在用户所在数据库登录,管理员需要通过admin认证后才能管理其他数据库

[root@localhost zhangy]# mongo
MongoDB shell version: 2.4.6
connecting to: tank
> show dbs;           //显示所有数据库失败,因为还没有认证
Wed Dec  4 06:39:50.925 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46
> db.auth('tank','test');    //认证失败,因为这个用户不属于tank这个数据库
Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" }
0
> use admin        //切换到admin数据库
switched to db admin
> db.auth('tank','test');   //在admin数据库认证成功
1
> use tank;           //切换到tank数据库
switched to db tank
> show collections;   //不会在提示没有权限了
contact
system.indexes
users

五,添加普通用启

> use tank;
switched to db tank
> db.addUser('tank1','test');     //为tank数据库添加了一个可读写用户tank1
{
    "_id" : ObjectId("529e5f8474b4c660718a70f3"),
    "user" : "tank1",
    "readOnly" : false,
    "pwd" : "35dd47abff098f5b4f0b567db8edeac5"
}
> db.addUser('tank2','test',true);  //为tank数据库添加了一个只读用户tank2
{
    "user" : "tank2",
    "readOnly" : true,
    "pwd" : "1792916c544d247538ded52e6df7b887",
    "_id" : ObjectId("529e67553992b24438d5e315")
}
> exit    //退出
bye
[root@localhost zhangy]# mongo
MongoDB shell version: 2.4.6
connecting to: tank
> db.auth('tank1','test');    //刚添加的用户可以登录。
1

六,php客户端连接

1, 推荐方法一

$mongo = new Mongo();    
$db = $mongo->selectDB('tank');   //切换到tank数据库  
$db->authenticate("tank3", "test");   //认证
$users= $db->selectCollection("users");  //选取users表
$cursor = $users->find();   //读取数据
foreach ($cursor as $id => $value) {
    echo "$id: "; print_r($value); echo "";
}

这种方式比较好理解,根命令行下的操作过程差不多。

2,推荐方法二

$mongo = new Mongo("mongodb://tank3:test@127.0.0.1:27017/tank");   //认证用户,这里的数据库,只启认证作用
$db = $mongo->selectDB('tank');  //选取数据库
$users= $db->selectCollection("users");
$cursor = $users->find();
foreach ($cursor as $id => $value) {
    echo "$id: "; print_r($value); echo "";
}

上面二种方法的不同在于,一个先选数据库在认证,一个先认证在选数据库。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools