How to grant privileges to a user in MongoDB using PHP?

by haylee.mertz , in category: PHP Databases , 2 years ago

How to grant privileges to a user in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 2 years ago

@haylee.mertz 

To grant privileges to a user in MongoDB using PHP, you can use the MongoDBCollection::command() method to run the createUser command.


Here's an example of how to grant privileges to a user in MongoDB using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

// Connect to MongoDB
$mongo = new MongoDBClient("mongodb://localhost:27017");

// Select the database
$database = $mongo->mydatabase;

// Select the users collection
$users = $database->users;

// Define the username and password
$username = "myuser";
$password = "mypassword";

// Define the roles to be granted to the user
$roles = [
    [
        "role" => "readWrite",
        "db" => "mydatabase"
    ]
];

// Create the user with the specified roles
$result = $database->command([
    "createUser" => $username,
    "pwd" => $password,
    "roles" => $roles
]);

// Print the result
print_r($result);

?>


In this example, we first connect to MongoDB using the MongoDBClient class. We then select the database and collection that we want to work with.


We define the username and password for the user that we want to create, and we define the roles that we want to grant to the user.


We then use the createUser command to create the user and grant the specified roles. We pass the command as an array to the command() method of the database object.


Finally, we print the result of the command using print_r(). The result should indicate that the user was created successfully.