All Products
Search
Document Center

ApsaraDB for MongoDB:Manage database accounts using the mongo shell

Last Updated:Mar 28, 2026

The mongo shell is a database management tool included with MongoDB. This topic describes how to create and query database accounts in ApsaraDB for MongoDB using the mongo shell.

Accounts created through the mongo shell do not appear on the Accounts page in the ApsaraDB for MongoDB console.

Prerequisites

Before you begin, ensure that you have:

Account names must be unique within a database.

Create a database account

Accounts created through the mongo shell do not appear on the Accounts page in the ApsaraDB for MongoDB console.
When you create a database account using the mongo shell for the first time, you must authenticate the built-in root account of the instance in the admin database.

Step 1: Switch to the admin database and authenticate

  1. Switch to the admin database:

    use admin
  2. Authenticate using the built-in root account:

    db.auth("root", "<password>")

    Replace <password> with the password of the root account.

Step 2: (Optional) Create a custom role

Skip this step if built-in roles meet your access requirements. Create a custom role when you need fine-grained access control over a specific collection.

A role is scoped to the database where it is created. To use a role across multiple databases, create it in the admin database. For more information, see createRole.

Switch to the target database before running db.createRole():

use <database_name>

Syntax:

db.createRole({
  role: "<role_name>",
  privileges: [{
    resource: { db: "<role_database_name>", collection: "<collection_name>" },
    actions: ["<action>"]
  }],
  roles: []
})
ParameterDescriptionExample
role_nameName of the new rolereadRole
role_database_nameDatabase the role applies totestDB
collection_nameCollection the role applies totestCollection
actionsAllowed operations, such as find, insert, update, and removefind
rolesRoles this role inherits. Must be included even when empty[]

Example: Create a role named readRole in the testDB database with find permission on the testCollection collection:

db.createRole({
  role: "readRole",
  privileges: [{
    resource: { db: "testDB", collection: "testCollection" },
    actions: ["find"]
  }],
  roles: []
})

Expected output:

{
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1747119397, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("fde8****", "hex"), 0),
      keyId: Long("7503****")
    }
  },
  operationTime: Timestamp({ t: 1747119397, i: 1 })
}

Step 3: Create the account

Three methods are available. All methods create an account by specifying a username, password, and roles.

If the account name contains special characters such as :/?#[]@, percent-encode them before use. For details, see Percent-Encoding.

Method 1: Switch to the target database first

Switch to the database where you want to create the account, then run db.createUser(). The account belongs to that database.

use <database_name>

Syntax:

db.createUser({
  user: "<user_name>",
  pwd: "<password>",
  roles: [{ role: "<role_name>", db: "<role_database_name>" }]
})
ParameterDescriptionExample
user_nameAccount nametest
passwordAccount password123456Aa
role_nameRole to assign. For valid values, see Roles of database accountsreadAnyDatabase
role_database_nameDatabase the role belongs to. For example, { role: "readAnyDatabase", db: "admin" } grants read-only access to all databasesadmin

Example: Create an account named test in the admin database with the readAnyDatabase role:

db.createUser({
  user: "test",
  pwd: "123456Aa",
  roles: [{ role: "readAnyDatabase", db: "admin" }]
})

Expected output:

Successfully added user: {
  "user" : "test",
  "roles" : [
    {
      "role" : "readAnyDatabase",
      "db" : "admin"
    }
  ]
}

Method 2: Create an account without switching databases

Use db.getMongo().getDB() or db.getSiblingDB() to target a specific database without switching context. Both methods accept the same parameters as Method 1.

db.getMongo()

Using `db.getMongo().getDB()`:

db.getMongo().getDB("<database_name>").createUser({
  user: "<user_name>",
  pwd: "<password>",
  roles: [{ role: "<role_name>", db: "<role_database_name>" }]
})

Example:

db.getMongo().getDB("admin").createUser({
  user: "test",
  pwd: "123456Aa",
  roles: [{ role: "readAnyDatabase", db: "admin" }]
})

db.getSiblingDB()

Using `db.getSiblingDB()`:

db.getSiblingDB("<database_name>").createUser({
  user: "<user_name>",
  pwd: "<password>",
  roles: [{ role: "<role_name>", db: "<role_database_name>" }]
})

Example:

db.getSiblingDB("admin").createUser({
  user: "test",
  pwd: "123456Aa",
  roles: [{ role: "readAnyDatabase", db: "admin" }]
})

Both methods return the same output as Method 1.

Query database accounts

Query all accounts in an instance

Run the following command in the admin database:

db.getCollection("system.users").find()
You can run this command without modification.

The response is shown below:

{ "_id" : "admin.root", "userId" : UUID("b079b4c8-0e34-4e0d-90f9-75741414****"), "user" : "root", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "WeN7mJumlZKG2dvzLRDL*****", "storedKey" : "wfRUnCq55ajFwnYxf9MQJ0k****", "serverKey" : "tP70xGJ9PRZs01VSJF1YDrHg****" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "5aIQ734c2Whg2pPwfg****/mpJulsd+33rE****", "storedKey" : "otMBwA2TTwoU****+dfwccnfPN14Dy5Oq6keYOl****", "serverKey" : "VCE****+aLkXGzCqRiaPfjnFG4WFiAOq0BKXxTo0****" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "admin.test", "userId" : UUID("769ea9a1-6224-470e-8162-19a62fa2****"), "user" : "test", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "8fyXsIUgs6aQmafhTDrS****", "storedKey" : "fJQFoKsl7ll****/4vFU4xQn****", "serverKey" : "Tf1zygJ****/3/P3UMM47rr8****" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "wcWRhs9VXEsmNWtd7ZD****+NbYXx8ugJ3p2****", "storedKey" : "A5GiH****/tf70hakRY3U3joho3GrtFWQ****/WX****", "serverKey" : "ryRAcj6zomYiHJqhA9ObvuYALc3ZZva8ImR7B89C****" } }, "roles" : [ { "role" : "readAnyDatabase", "db" : "admin" } ] }

Query all accounts in a specific database

You can run the use database_name command to switch databases, where database_name is the name of the target database.

Method 1: Switch to the target database and run:

show users
You can run this command without modification.

The response is shown below:

{
        "_id" : "admin.root",
        "userId" : UUID("b079b4c8-0e34-4e0d-90f9-75741414****"),
        "user" : "root",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}
{
        "_id" : "admin.test",
        "userId" : UUID("769ea9a1-6224-470e-8162-19a62fa2****"),
        "user" : "test",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "readAnyDatabase",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

Method 2: Run the following command in the admin database, replacing <database_name> with the target database name:

db.getCollection("system.users").find({ db: "<database_name>" })

Example:

db.getCollection("system.users").find({ db: "admin" })

The response is shown below:

{ "_id" : "admin.root", "userId" : UUID("b079b4c8-0e34-4e0d-90f9-75741414****"), "user" : "root", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "WeN7mJumlZKG2dvzLRDL*****", "storedKey" : "wfRUnCq55ajFwnYxf9MQJ0k****", "serverKey" : "tP70xGJ9PRZs01VSJF1YDrHg****" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "5aIQ734c2Whg2pPwfg****/mpJulsd+33rE****", "storedKey" : "otMBwA2TTwoU****+dfwccnfPN14Dy5Oq6keYOl****", "serverKey" : "VCE****+aLkXGzCqRiaPfjnFG4WFiAOq0BKXxTo0****" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "admin.test", "userId" : UUID("769ea9a1-6224-470e-8162-19a62fa2****"), "user" : "test", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "8fyXsIUgs6aQmafhTDrS****", "storedKey" : "fJQFoKsl7ll****/4vFU4xQn****", "serverKey" : "Tf1zygJ****/3/P3UMM47rr8****" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "wcWRhs9VXEsmNWtd7ZD****+NbYXx8ugJ3p2****", "storedKey" : "A5GiH****/tf70hakRY3U3joho3GrtFWQ****/WX****", "serverKey" : "ryRAcj6zomYiHJqhA9ObvuYALc3ZZva8ImR7B89C****" } }, "roles" : [ { "role" : "readAnyDatabase", "db" : "admin" } ] }

Query a specific account

The command to query a single database account must be run in the admin database.
db.getCollection("system.users").find({ user: "<user_name>", db: "<database_name>" })
ParameterDescription
user_nameName of the account
database_nameDatabase the account belongs to

Example:

db.getCollection("system.users").find({ user: "test", db: "admin" })

The response is shown below:

{ "_id" : "admin.test", "userId" : UUID("769ea9a1-6224-470e-8162-19a62fa2****"), "user" : "test", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "8fyXsIUgs6aQmafhTDrS****", "storedKey" : "fJQFoKsl7llXdiU/4vFU4xQn****", "serverKey" : "Tf1zygJ****/3/P3UMM47rr8****" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "wcWRhs9VXEsmNWtd7ZD****+NbYXx8ugJ3p2****", "storedKey" : "A5GiH****/tf70hakRY3U3joho3GrtFWQ****/WX****", "serverKey" : "ryRAcj6zomYiHJqhA9ObvuYALc3ZZva8ImR7B89C****" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }

Roles of database accounts

For the complete list of built-in roles, see Built-In Roles.
ScopeRoleDescription
All databasesreadOnlyRead-only permissions on the database
All databasesreadWriteRead and write permissions on the database
All databasesuserAdminPermissions to create accounts and roles in the database
All databasesdbAdminPermissions to manage collections in the database
All databasesdbOwnerAll permissions of readWrite, userAdmin, and dbAdmin
All databasesenableShardingAllows a database in a sharded cluster to be distributed across multiple shards
admin databasereadAnyDatabaseRead-only permissions on all databases
admin databasereadWriteAnyDatabaseRead and write permissions on all databases
admin databaseuserAdminAnyDatabasePermissions to create accounts and roles in all databases
admin databasedbAdminAnyDatabasePermissions to manage collections in all databases
admin databaseclusterMonitorPermissions to run various commands for collecting information
admin databasehostManagerPermissions to run commands such as setParameter, killop, resync, and killCursors
admin databaseclusterManagerPermissions to run node management commands
admin databaseclusterAdminAll permissions of clusterMonitor, hostManager, and clusterManager
admin databaserootAll admin database permissions, including readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase

What's next