Mongodb PHP驱动程序:如何创建数据库并向其中添加用户? [英] Mongodb PHP driver: how to create database and add user to it?
问题描述
因此,使用mongodb shell,我能够创建数据库并向其中添加用户名和密码.我如何在php中做同样的事情?我已经安装了所有东西,并且能够连接到mongodb服务器.
so using the mongodb shell, I was able to create a database and add a username and password to it. How can I do the same in php? I have everything installed and able to connect to mongodb server.
但是,我在文档.
推荐答案
我不相信addUser()
是在PHP驱动程序中实现的.
I do not believe addUser()
is implemented in the PHP driver.
但是,有一个 execute
应该允许您执行addUser()
的方式与在mongo shell中执行的方式相同:
However, there is an execute
that should allow you to do an addUser()
the same way you would from the mongo shell:
经过测试,我无法获得 execute
做您想做的事,但我确实发现以下工作有效:
After testing, I couldn't get execute
to do what you wanted, but I did find that the following works:
<?php
// open connection
$mongo = new Mongo("mongodb://" . MONGO_USER . ":" . MONGO_PASS . "@" . MONGO_HOST, array("persist" => "abcd1234"));
$db = $mongo->selectDB("admin");
// user info to add
$username = "testUser";
$password = "testPassword";
// insert the user - note that the password gets hashed as 'username:mongo:password'
// set readOnly to true if user should not have insert/delete privs
$collection = $db->selectCollection("system.users");
$collection->insert(array('user' => $username, 'pwd' => md5($username . ":mongo:" . $password), 'readOnly' => false));
?>
这会将新用户添加到我服务器上的admin数据库中-在执行PHP脚本后通过mongo shell进行检查.
That adds a new user to the admin db on my server - checked via mongo shell after executing PHP script.
也就是说-为什么要从PHP脚本添加Mongo用户?
That said - why do you want to add a Mongo user from a PHP script?
这篇关于Mongodb PHP驱动程序:如何创建数据库并向其中添加用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!