Create a MongoDB user from Compass

TL, DR

MongoDB is one of the leading NoSQL databases, and Compass is its desktop GUI. We will see how we can leverage it to create new users.

Creating users from Compass

I already provided an introduction to MongoDB and Compass in a previous post for my MongoDB series. In this post we will explore how to create new users in your MongoDB from Compass.

The first thing you need to do, once you are connected to your MongoDB in Compass, is to enter the shell. You can do it by clicking on the >_ icon next to the name of your MongoDB instance.

Once your are in the shell, the first command you need to input is the one to select in which database you want to create the new user. For instance, into myTestDB:

use myTestDB

The second command is the one to create the user. To keep things simple, we will use the username / password authentication. Remember that several special characters ($ : / ? # [ ] @) needs to be converted with percent-encoding in connection strings.

db.createUser(
  {
    user: "myUser",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "myTestDB" },
             { role: "read", db: "anotherDB" } ]
  }
)

You can assign multiple roles in different DBs at once. For authentication of the new user you created, the best practice is to run it against the specific database where you create the user, by specifying the database name in the MongoDB connection string. For instance:

mongodb://myUser:<pwd>@192.168.1.247:27017/myTestDB?tls=false

I hope you find this useful! I plan to write more MongoDB-related posts over time, you can check them here!

  • MongoDB manual link
  • MongoDB related posts link

Do you like our content? Check more of our posts in our blog!