Dragonfly

Question: How do you create a user for a MongoDB cluster?

Answer

Creating a user in a MongoDB cluster is an essential step in managing access and ensuring security. MongoDB provides role-based access control (RBAC) that allows you to specify the exact capabilities a user has within your database environment. Here's how to create a new user with specific roles.

Prerequisites

Steps to Create a User

  1. Connect to the MongoDB shell:
    First, connect to your MongoDB instance or cluster. If you are using mongosh, the new MongoDB Shell, you can connect using:
mongosh \"mongodb+srv://cluster0.example.mongodb.net/myFirstDatabase\" --username myAdminUser

Replace the connection string with your cluster’s information.

  1. Switch to the admin database:
    Most user management operations need to be done from the admin database:
use admin
  1. Create the user:
    You can now create a new user by using the createUser command. This command allows you to specify the username, password, and roles for the new user.

Here's an example of creating a user named myNewUser with read and write access to the myDatabase database:

db.createUser({
  user: \"myNewUser\",
  pwd: \"password123\", // You can also use a more secure method to generate and store passwords
  roles: [
    { role: \"readWrite\", db: \"myDatabase\" }
  ]
})

Replace myNewUser, password123, and myDatabase with the desired username, secure password, and the database name where you want the user to have specific roles.

Additional Notes

Creating users with appropriate roles is crucial for maintaining the security and integrity of your data in MongoDB. By following these steps, you can effectively manage access to your MongoDB cluster.

Was this content helpful?

Other Common MongoDB Performance Questions (and Answers)

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost