Mongodb PHP driver: how to create database and add

2020-07-24 05:03发布

问题:

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.

However, I can't find any information in the doc.

回答1:

I do not believe addUser() is implemented in the PHP driver.

However, there is an execute that should allow you to do an addUser() the same way you would from the mongo shell:

EDIT: 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));
?>

That adds a new user to the admin db on my server - checked via mongo shell after executing PHP script.

That said - why do you want to add a Mongo user from a PHP script?



回答2:

A way to create a new mongodb user from PHP is via MongoDB::command:

//info to add
$db_name = 'db_name';
$db_user = 'new_user';
$db_pass = 'new_pass';

//autenticate with a user who can create other users
$mongo = new MongoClient("mongodb://root:root@localhost/admin");
$db = $mongo->selectDB( $db_name );

//command to create a new user
$command = array
(
    "createUser" => $db_user,
    "pwd"        => $db_pass,
    "roles"      => array
    (
        array("role" => "readWrite", "db" => $db_name)
    )
);

//call MongoDB::command to create user in 'db_name' database
$db->command( $command );

Tested with mongo 3.0 and PHP mongo driver 1.6



标签: php mongodb