createUser (Create User)
Last updated: 2026-10-09
createUser (Create User)
createUser creates a database user with roles; in mongosh use db.createUser({ user, pwd, roles }). Roles can be built-in (read, readWrite, dbAdmin, root) or custom, scoped across databases with { role, db } objects. The user belongs to the database the command runs on. Authentication only takes effect when authorization is enabled.
| Category | User Authentication |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.createUser({
user: "<username>",
pwd: "<password>",
roles: [ { role: "readWrite", db: "shop" } ]
})
⚙️ Parameters
| user | The username |
|---|---|
| pwd | The password; passwordDigestor can control hashing |
| roles | Role list as { role, db } objects or strings |
Returns:Returns { ok: 1 } on success
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// createUser: create a read-only user
use admin
db.createUser({
user: 'reader',
pwd: 'secret123',
roles: [ { role: 'read', db: 'shop' } ]
})
Output:
{ ok: 1 }
📌 Notes
- The user belongs to the db where createUser runs
- Authorize across databases with { role, db }
- Passwords are not stored in plaintext, but still use strong ones
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhich database should createUser run on?
AOn the database the user belongs to (usually admin or the business db); scope cross-db roles with { role, db }.
QUsers were created but connections skip authentication?
AMongoDB checks credentials only when authorization is enabled; otherwise anyone can connect.
QWhat are the built-in roles?
Aread, readWrite, dbAdmin, dbOwner, userAdmin, root, and others.