Home Database Mysql Tutorial mongodb 用户 权限 设置 详解

mongodb 用户 权限 设置 详解

Jun 07, 2016 pm 04:32 PM
mongodb Relational database Permissions user Know set up Detailed 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")
}
Copy after login

三,开启动用户权限认证

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

四,用户只能在用户所在数据库登录,管理员需要通过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
Copy after login

五,添加普通用启

> 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
Copy after login

六,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 "";
}
Copy after login

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

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 "";
}
Copy after login

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

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Enable root permissions with one click (quickly obtain root permissions) Enable root permissions with one click (quickly obtain root permissions) Jun 02, 2024 pm 05:32 PM

It allows users to perform more in-depth operations and customization of the system. Root permission is an administrator permission in the Android system. Obtaining root privileges usually requires a series of tedious steps, which may not be very friendly to ordinary users, however. By enabling root permissions with one click, this article will introduce a simple and effective method to help users easily obtain system permissions. Understand the importance and risks of root permissions and have greater freedom. Root permissions allow users to fully control the mobile phone system. Strengthen security controls, customize themes, and users can delete pre-installed applications. For example, accidentally deleting system files causing system crashes, excessive use of root privileges, and inadvertent installation of malware are also risky, however. Before using root privileges

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Is it difficult to learn nodejs on the front end? Is it difficult to learn nodejs on the front end? Apr 21, 2024 am 04:57 AM

For front-end developers, the difficulty of learning Node.js depends on their JavaScript foundation, server-side programming experience, command line familiarity, and learning style. The learning curve includes entry-level and advanced-level modules focusing on fundamental concepts, server-side architecture, database integration, and asynchronous programming. Overall, learning Node.js is not difficult for developers who have a solid foundation in JavaScript and are willing to invest the time and effort, but for those who lack relevant experience, there may be certain challenges to overcome.

What to do if navicat expires What to do if navicat expires Apr 23, 2024 pm 12:12 PM

Solutions to resolve Navicat expiration issues include: renew the license; uninstall and reinstall; disable automatic updates; use Navicat Premium Essentials free version; contact Navicat customer support.

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How does Go WebSocket integrate with databases? How does Go WebSocket integrate with databases? Jun 05, 2024 pm 03:18 PM

How to integrate GoWebSocket with a database: Set up a database connection: Use the database/sql package to connect to the database. Store WebSocket messages to the database: Use the INSERT statement to insert the message into the database. Retrieve WebSocket messages from the database: Use the SELECT statement to retrieve messages from the database.

See all articles