mongo-db
  1. mongo-db-user-management-methods

User Management Methods - ( MongoDB Shell )

MongoDB provides various user management methods to create users, assign roles, and modify user privileges. In this page, we will discuss the user management methods of MongoDB shell.

Syntax

The syntax for creating a MongoDB user is as follows:

db.createUser({
   user: "username",
   pwd: "password",
   roles: [
      { role: "readWrite", db: "database" },
      { role: "read", db: "otherDatabase" }
   ]
})

The syntax for deleting a MongoDB user is as follows:

db.dropUser("username")

Example

Here's an example of creating a MongoDB user with readWrite role on a database named sampledb.

use sampledb
db.createUser({
   user: "jsmith",
   pwd: "password",
   roles: [
      { role: "readWrite", db: "sampledb" }
   ]
})

Here's an example of deleting the MongoDB user jsmith.

use sampledb
db.dropUser("jsmith")

Output

When you create a new user in MongoDB, the output will be Successfully added user. When you delete a user in MongoDB, the output will be true.

Explanation

In MongoDB, you can create a user with a specified username and password credentials. You also need to specify roles for the user, which define what actions the user can perform in databases or collections. For example, the readWrite role allows the user to read, write, and modify data, while the read role only allows the user to read data.

If you need to delete a user from a MongoDB database, you can use the dropUser() method. This method permanently deletes the user and any associated credentials from the database.

Use

MongoDB user management methods are useful for managing access to your data and ensuring that only authorized users can access databases and collections.

Important Points

  • User management methods are executed in the MongoDB shell.
  • You need to specify a username, password, and roles while creating a MongoDB user.
  • You can select a database using the use command before creating or deleting a MongoDB user.
  • The dropUser() method is used to delete a user and its associated credentials from a MongoDB database.

Summary

In this page, we discussed the user management methods of MongoDB shell. We covered the syntax, example, output, explanation, use, important points, and summary of user management methods in MongoDB. By using these methods, you can manage MongoDB users, assign roles, and modify user privileges to ensure that only authorized users can access your MongoDB data.

Published on: