Home >Database >MongoDB >How to create a user in MongoDB v3?

How to create a user in MongoDB v3?

PHPz
PHPzforward
2023-09-13 11:05:02751browse

如何在 MongoDB v3 中创建用户?

To create a user in MongoDB v3, use the createUser() method. This allows you to create a user and upon creation also add the user, password and role. These roles assign permissions. The syntax is as follows -

use admin
db.createUser(
   {
      user: “yourUserName",
      pwd: "yourPassword",
      roles: [ { role: "yourPermission", db: "yourDatabase" } ]
   }
);

Let us implement the above syntax to create a user in MongoDB v3 -

> use admin
switched to db admin
> db.createUser(
...    {
...       user: "Robert",
...       pwd: "robert",
...       roles: [ { role: "readWrite", db: "sample" } ]
...    }
... );

Above, we have set the following for the new user -

User: Robert
Password: robert
Roles: readWrite
This will produce the following output:
Successfully added user: {
   "user" : "Robert",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "sample"
      }
   ]
}

us A new user "Robert" has been successfully created above.

The above is the detailed content of How to create a user in MongoDB v3?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete