How to create a user in MongoDB
Create MongoDB users with db.createUser(): an admin user, an app user with readWrite on one database, and the authSource you need to log in as them.
Quick Answer
Switch to the database the user belongs to, then call db.createUser() with a name, password and roles:
use shop
db.createUser({
user: 'shop_app',
pwd: passwordPrompt(), // or a string
roles: [{ role: 'readWrite', db: 'shop' }]
})
The user then logs in with authSource=shop, because that's the database it was created in.
Create an admin user first
On a fresh server with access control turned on, there are no users yet. MongoDB lets a connection from localhost create the first one (the localhost exception). Make it an admin in the admin database:
use admin
db.createUser({
user: 'admin',
pwd: passwordPrompt(),
roles: [
{ role: 'userAdminAnyDatabase', db: 'admin' },
{ role: 'readWriteAnyDatabase', db: 'admin' }
]
})
passwordPrompt() asks for the password interactively, so it never lands in your shell history. Use roles: ['root'] instead if you want one superuser that can do everything, including cluster operations.
Users only matter once authorization is on. For a self-managed server, set security.authorization: enabled in mongod.conf (or start mongod with --auth) and restart. Without it, anyone who can reach the port can do anything, whatever users exist.
Create an app user for one database
Applications should get a user that can only touch their own database. Create it in that database:
use shop
db.createUser({
user: 'shop_app',
pwd: passwordPrompt(),
roles: ['readWrite'] // a bare role name means "on this database"
})
A role can also point at a different database, so one user can write to one and read another:
db.createUser({
user: 'reporting',
pwd: passwordPrompt(),
roles: [
{ role: 'read', db: 'shop' },
{ role: 'readWrite', db: 'reports' }
]
})
Which role to give
| Role | Grants | Defined on |
|---|---|---|
read | Query any collection in the database | Any database |
readWrite | Read plus insert, update, delete, create and drop collections and indexes | Any database |
dbAdmin | Indexes, stats, validation and profiling, but not reading data | Any database |
userAdmin | Create and manage users and roles on that database | Any database |
dbOwner | readWrite + dbAdmin + userAdmin | Any database |
readAnyDatabase | read on every database | admin only |
readWriteAnyDatabase | readWrite on every database | admin only |
userAdminAnyDatabase | Manage users on every database | admin only |
root | Everything | admin only |
The "AnyDatabase" roles and root only exist in admin. Granting one while you're in another database fails with Could not find role: readAnyDatabase@shop; pass { role: 'readAnyDatabase', db: 'admin' } instead.
For custom roles and how privileges combine, see our guide to MongoDB users, roles and permissions.
Log in as the new user
A user is stored with the database it was created in, its authentication database. Tell the client where to find it with authSource:
# user created in shop
mongosh "mongodb://shop_app@localhost:27017/shop?authSource=shop"
# user created in admin
mongosh "mongodb://admin@localhost:27017/?authSource=admin"
If the connection string names a database and no authSource, the client authenticates against that database. Logging in as an admin-database user while connected to /shop fails with "Authentication failed" for exactly that reason.
From Node.js or Python
Drivers have no createUser helper. Run the database command directly:
const db = client.db('shop')
await db.command({
createUser: 'shop_app',
pwd: process.env.SHOP_APP_PASSWORD,
roles: [{ role: 'readWrite', db: 'shop' }]
})
import os
db = client["shop"]
db.command(
"createUser", "shop_app",
pwd=os.environ["SHOP_APP_PASSWORD"],
roles=[{"role": "readWrite", "db": "shop"}],
)
The connecting user needs userAdmin on that database, or userAdminAnyDatabase.
What we found testing this
We ran these on a MongoDB 7.0 server with authorization turned on.
1. Creating a user doesn't create its database
After use shop and db.createUser(...), shop still isn't in show dbs. The user lives in admin.system.users with the id 'shop.shop_app'. It can log in straight away, and its first insert creates the database.
2. A new user can't list users, not even itself
Logged in as a plain readWrite user, show users fails, but asking about yourself by name works:
show users
// MongoServerError: not authorized on shop to execute command { usersInfo: 1, ... }
db.runCommand({ usersInfo: 'shop_app' }).users[0].roles
// [ { role: 'readWrite', db: 'shop' } ]
3. Every user gets two password hashes unless you say otherwise
By default a user is created with both SCRAM-SHA-1 and SCRAM-SHA-256 credentials. Pass mechanisms: ['SCRAM-SHA-256'] to store only the stronger one. Old clients that force SHA-1 then fail with a clear message, so you'll know at once if one still exists:
mongosh "mongodb://shop_app@localhost:27017/shop?authMechanism=SCRAM-SHA-1"
# MongoServerError: Unable to use SCRAM-SHA-1 based authentication for user
# without any SCRAM-SHA-1 credentials registered
4. A wrong authSource gives no hint
Connecting as a shop user with authSource=admin returns only MongoServerError: Authentication failed., exactly the same as a wrong password. If the password is definitely right, check authSource first.
Common errors
User "shop_app@shop" already exists(code 51003): usedb.updateUser('shop_app', { ... })to change roles, ordb.changeUserPassword()to reset the password.not authorized on shop to execute command { createUser: ... }: the user you're logged in as can't manage users there. Log in as an admin.- MongoDB Atlas:
db.createUser()isn't allowed. Create database users under Database Access in the Atlas UI, or with the Atlas CLI.
Frequently Asked Questions
Which database should I create a user in?
Either the database the application uses, or admin if you manage all users centrally. Both work; just use the matching authSource when connecting.
How do I give a user access to every database?
Create it in admin with readWriteAnyDatabase (or readAnyDatabase for read-only). Those roles only exist in the admin database.
Can I create a user without access control enabled?
Yes, and it is a good way to prepare users before turning authorization on. They will not be enforced until security.authorization is enabled.
How do I see the users I created?
Run show users, or db.getUsers(), in the database the users were created in. See the list users guide for listing across all databases.