Hey there, tech enthusiast!

Today, we'll learn how to create a new user in MongoDB with admin privileges. This is a crucial step for database security, so let's make it happen!

⏱️ Estimated time: 5 minutes

Before We Start 📝

Make sure:

  • MongoDB is installed and running
  • You have access to the terminal
  • MongoDB service is active

Pro tip: Always use strong passwords in production environments!

Let's Create a MongoDB User 👤

  1. First, connect to MongoDB shell:
mongosh
💡
Note: You're good to go if you see a connection message!
  1. Switch to admin database:
use admin
💡
A quick tip: The 'admin' database stores user information by default.
  1. Create your new user 🆕
db.createUser({  
  user: "root",  
  pwd: "password",  
  roles: [ "userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase" ]  
})  

Let's break down those roles 📚

The roles we're assigning here are pretty powerful:

  • userAdminAnyDatabase: Can manage users for any database
  • dbAdminAnyDatabase: Can perform admin tasks on all databases
  • readWriteAnyDatabase: Can read and write to any database

⚠️ Security Note:
Remember to:

  • Change "password" to a strong password
  • Store credentials securely
  • Never share your admin passwords
  1. Exit the MongoDB shell:
quit

Verification Step ✅

You can test your new user by logging in with these credentials.

Common Issues & Solutions 🔧

  1. If you get an "Authentication failed" error:
    • Double-check your password
    • Ensure you're using the correct database
  2. If you can't create a user:
    • Verify you're in the admin database
    • Check if you have sufficient privileges

Additional Tips 💡

  • Keep your passwords complex and secure
  • Document your user credentials safely
  • Regular audit of user access is recommended
  • Consider using environment variables for passwords in production

⏱️ That's it! In just about 5 minutes, you've successfully created a MongoDB admin user.

Need to add more users or modify roles? Drop a comment below, and I'll help you out! Happy database managing! 🚀

Pro tip: Save these commands somewhere safe - you might need them again for future database setups!

Share this post