SKDBLOG

DevOps

MongoDB Admin User Setup with mongosh: createUser, Roles & Verification

Provision a localhost bootstrap admin persona with mongosh db.createUser on the admin database, unpack userAdminAnyDatabase, dbAdminAnyDatabase, and readWriteAnyDatabase trade-offs, authenticate to prove SCRAM sticks, then untangle the usual Authentication failed loops without oversharing superuser accounts.

Shashikant Dwivedi
3 min read
MongoDB Admin User Setup with mongosh: createUser, Roles & Verification
DevOps03 MIN

Provisioning a hardened admin persona belongs on almost every MongoDB 7 on Ubuntu install before teammates lean on Compass or Drivers. Assume this host still defaults to trusting localhost first; widen networking only after aligning bind addresses and auth with how to enable MongoDB remote connections safely. When Ubuntu services need a sibling reverse proxy snippet, tuck Ubuntu Nginx install commands next to whatever automation you reuse.

⏱️ Estimated effort: roughly five uninterrupted minutes assuming mongod already listens and you can rerun mongosh twice for an anonymous session versus an authenticated sanity check.

Before you begin

  • MongoDB is installed, started, and answers on whatever socket or host you intend to bootstrap.
  • Terminal access reaches that host locally (this walkthrough prioritizes trusting loopback paths first).
  • You have latitude to jot down ephemeral passwords before rotating them through your secret manager.

Connect with mongosh and use admin

  1. Attach the shell (mongosh assumes localhost listeners once your MongoDB 7 on Ubuntu install is answering cleanly):
bash
mongosh

Notice how MongoDB echoes the replica set or standalone metadata right away—you only continue once no TLS or handshake errors obscure the banner.

  1. Point the shell at the canonical auth database administrators expect:
bash
use admin

Administrative users usually live alongside other cluster metadata collections here—linking schemas through authenticationDatabase admin downstream becomes predictable.

Create an admin-capable user

  1. Instantiate the persona with db.createUser. Duplicate the role names verbatim or MongoDB rejects the privilege document:
javascript
db.createUser({
  user: "root",
  pwd: "password",
  roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"],
})

Treat "password" as a throwaway you replace before anyone else clones the wiki—prefer reading secrets from ephemeral environment variables injected by your provisioning layer.

Exit when you finish editing metadata so the driver negotiates cleanly on the next hop:

bash
quit()

Understand the roles you just granted

  • userAdminAnyDatabase — create, rename, revoke, or sync credentials spanning every logical database (userAdmin* scopes stay sharper than blindly granting root where vendors forbid it outright).
  • dbAdminAnyDatabase — compaction, profiling, collation tuning, indexes, capped collection maintenance—anything schema-adjacent that is not purely document CRUD lives here.
  • readWriteAnyDatabase — unrestricted document reads and mutations across namespaces; combine it with the preceding pair only while you consciously accept super-operator semantics.

Verify the account

Spin up another shell authenticated against the admin database so SCRAM proofs match ops runbooks:

bash
mongosh -u root -p --authenticationDatabase admin

Type the password interactively—or template a URI—but keep authSource=admin visible so drivers stop throwing Authentication failed when they default authSource to the application's working database (mongodb://root:@localhost:27017/admin style URIs omit secrets here on purpose).

Common issues and fixes

  1. Authentication failed loops
    • Re-type the credential carefully; keyboards love hiding trailing spaces copied from spreadsheets.
    • Confirm mongosh targets the same daemon where you authored the document—cluster upgrades sometimes leave orphaned configdb paths.
    • Pass --authenticationDatabase admin explicitly; omitting it steers SCRAM lookups toward the application's default database metadata.
  2. Cannot run createUser
    • Ensure you genuinely executed use admin before emitting the BSON document.
    • Verify the session still runs before --auth; otherwise privilege checks prematurely block DDL.

Security habits worth keeping

  • Rotate privileged passwords out of plaintext scripts the moment onboarding finishes.
  • Store recovery codes in audited vault entries instead of ephemeral chat threads nobody replays quarterly.
  • Revisit delegated access during compliance reviews—even MongoDB Compass sessions inherit whatever roles linger on these accounts.

Frequently asked questions

Why create privileged MongoDB accounts in the admin database?

MongoDB persists user documents under admin by convention during localhost bootstrap workflows: you run use admin before db.createUser so metadata lands where operators expect, simplifying future authSource lookups and tooling automation.

Do I always need userAdminAnyDatabase, dbAdminAnyDatabase, and readWriteAnyDatabase together?

The triple stack mimics classic super-operator freedom for lab servers or migration windows. Narrower custom roles satisfy production least privilege workloads so leaked passwords cannot reorganize schemas or redefine every downstream credential outright.

What causes Authentication failed errors right after db.createUser?

Typical culprits include mistyped passwords, connecting without --authenticationDatabase admin despite defining the user in admin, restarting agents against stale configuration files, or testing before --auth binds to the mongod instance you mutated.

Does this admin persona replace binding MongoDB safely for remote access?

Network exposure remains independent from authorization semantics: tighten net.bindIp, perimeter firewalls, and TLS transports before leaning on SCRAM passwords alone wherever remote workloads need the service—as tied into MongoDB remote access planning.

How does this localhost flow tie into installing MongoDB on Ubuntu?

Pair these mongosh steps once apt packages and systemctl restart mongod settle so UNIX sockets answer locally before widening bindIp for WAN workloads or migrating uptime to hosted MongoDB services.

Written by Shashikant Dwivedi

Engineer, occasional writer, full-time noticer. Based in Prayagraj, India. New essays land roughly twice a month.

Keep reading

Adjacent essays.

All writing →

The newsletter

New articles in your inbox.

Occasional articles on engineering, tooling, and software development practices. No marketing, no fluff — just the article, when it's ready.

Unsubscribe with one click. Your email never leaves the list.