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


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.


  • Ensure that you have admin access to the MongoDB cluster.
  • Make sure that the MongoDB service is running.

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://\" --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

  • The role(s) you assign to a user can vary greatly depending on your security and operational requirements. MongoDB offers a wide range of built-in roles like read, readWrite, dbAdmin, etc.
  • Consider using custom roles if the built-in roles don’t exactly match your needs.
  • Always ensure that passwords are stored securely and follow best practices for password management.

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?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.