A while back I made a write up documenting creating a Postgres user, I find myself going back and using it as a point reference. That's partly the motivation for this blog, a public and personal knowledge base; I mention that in my intro post. Another database I frequently use is MongoDB and here's how you can create a user.
Prerequisites
- A MongoDB instance somewhere, you could create one in DigitalOcean to try this
- An understanding of how to get shell access to your MongoDB server, you can do this with mongosh
- Optional: A MongoDB GUI, I use MongoDB Compass it has everything you need (including a shell)
Note: The article assumes you have an active shell to your MongoDB instance, here are some docs on how to connect with mongosh and with MongoDB Compass.
Why?
I like to create a separate database and user any time I create an app deployment using MongoDB. These are often running in my production clusters (like this blog) or if I have an idea and start another project locally, for me that happens frequently. Recently, I also recreated my local MongoDB instance as a StatefulSet on K3s and I've mentioned K3s a few times (so far here and last week here). Each of these actions require me to do the task of user creation fairly often and the steps below are the steps I always take for the task.
1. The Database
MongoDB allows individual databases to manage their own users, so the first step is to make sure your database exists. To create it just run this command in the shell (replace create-user-example-db with your database name):
Keep that shell open!
2. The User
Next step is to create a user that you can connect with on this database. Run this in the same shell you used above (replace the command parameters to match your values):
Here's the official documentation for the readWrite user role capabilities.
This will create a user in the create-user-example-db, so the authSource parameter in your connection string needs to be this database. You can read about that parameter for your connection string on the MongoDB docs.
3. The Connection
Now you should be able to connect to the database with that user:
Note: the authSource parameter is not included in this string because it defaults to the database being connected to if it isn't provided.
Conclusion
And that's how you can create a user for your MongoDB database. It's a quick point of reference for creating a database, a new user, and a connection with that user. Happy coding! 🧑💻