All Products
Search
Document Center

ApsaraDB for MongoDB:Manage database accounts using the mongo shell

Last Updated:Jul 17, 2026

The mongo shell is a database management tool included with MongoDB. You can use the mongo shell to create and query database accounts in ApsaraDB for MongoDB.

Prerequisites

  1. An ApsaraDB for MongoDB instance is created. For more information about how to create different types of instances, see the following topics:

  2. You are connected to the ApsaraDB for MongoDB instance by using the mongo shell. For more information about how to connect to different types of instances, see the following topics:

Precautions

Database accounts must be unique within a database.

Create a database account

Note
  • Database accounts that are created using the mongo shell are not displayed 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.

  1. Switch to the admin database.

    use admin
    Note

    You can run this command without modification.

  2. Authenticate the root account.

    Syntax:

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

    Parameter description: password specifies the password of the root account.

    Example:

    db.auth("root","123456Aa")
  3. (Optional) Create a custom database role.

    To restrict access to a specific collection, create a custom database role for fine-grained access control.

    • Switch databases: Run the use database_name command to switch to the target database, where database_name is the name of the target database.

    • Role scope: A role can be used only in the database in which it is created. If a role applies to multiple databases, you must create the role in the admin database.

    Syntax:

    db.createRole({role: "role_name", privileges: [{resource: {db: "role_database_name", collection: "collection_name" }, actions: [ "actions" ] }],roles: []})

    Parameter description:

    Parameter

    Description

    Example

    role_name

    The name of the new role.

    readRole

    role_database_name

    The database on which the role has operation permissions.

    testDB

    collection_name

    The name of the collection.

    testCollection

    actions

    The allowed operation types, such as find, insert, update, and remove.

    find

    roles

    Other roles that this role inherits. An empty array indicates no inheritance, but the roles field is required.

    []

    Note

    For more information, see createRole.

    Example:

    Create a role named readRole in the testDB database and grant it the find permission on the testCollection collection.

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

    A successful response looks like the following:

    {
      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 })
    }
  4. Create a database account.

    Method 1: Switch to the target database to create an account

    A database account belongs to the database where it is created.

    Run the use database_name command to switch to a database, where database_name is the name of the target database.

    Syntax:

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

    Parameter description:

    Parameter

    Description

    Example

    user_name

    The name of the database account.

    If the account name contains special characters, such as :/?#[]@, you must percent-encode the special characters. For information about how to perform percent encoding, see Percent-Encoding.

    test

    password

    The password of the database account.

    123456Aa

    role_name

    The role to grant to the database account.

    For more information about the valid values, see Roles of database accounts.

    readAnyDatabase

    role_database_name

    The name of the database to which the role belongs.

    For example, {role: "readAnyDatabase", db: "admin"} grants the readAnyDatabase role of the admin database to the account. This provides read-only permissions on all databases.

    admin

    Example:

    Create a database account named test in the admin database, set the password to 123456Aa, and grant the readAnyDatabase role to the test account.

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

    A successful response looks like the following:

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

    Method 2: Create an account without switching databases

    You can use one of the following methods to create a database account without switching databases.

    db.getMongo()

    Syntax:

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

    Parameter description:

    Parameter

    Description

    Example

    database_name

    The name of the database to which the account belongs.

    admin

    user_name

    The name of the database account.

    If the account name contains special characters, such as :/?#[]@, you must percent-encode the special characters. For information about how to perform percent encoding, see Percent-Encoding.

    test

    password

    The password of the database account.

    123456Aa

    role_name

    The role to grant to the database account.

    For more information about the valid values, see Roles of database accounts.

    readAnyDatabase

    role_database_name

    The name of the database to which the role belongs.

    For example, {role: "readAnyDatabase", db: "admin"} grants the readAnyDatabase role of the admin database to the account. This provides read-only permissions on all databases.

    admin

    Example:

    Create a database account named test that belongs to the admin database, set the password to 123456Aa, and grant the readAnyDatabase role to the test account.

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

    A successful response looks like the following:

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

    db.getSiblingDB()

    Syntax:

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

    Parameter description:

    Parameter

    Description

    Example

    database_name

    The name of the database to which the account belongs.

    admin

    user_name

    The name of the database account.

    If the account name contains special characters, such as :/?#[]@, you must percent-encode the special characters. For information about how to perform percent encoding, see Percent-Encoding.

    test

    password

    The password of the database account.

    123456Aa

    role_name

    The role to grant to the database account.

    For more information about the valid values, see Roles of database accounts.

    readAnyDatabase

    role_database_name

    The name of the database to which the role belongs.

    For example, {role: "readAnyDatabase", db: "admin"} grants the readAnyDatabase role of the admin database to the account. This provides read-only permissions on all databases.

    admin

    Example:

    Create a database account named test that belongs to the admin database, set the password to 123456Aa, and grant the readAnyDatabase role to the test account.

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

    A successful response looks like the following:

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

Query database accounts

Query all database accounts of an ApsaraDB for MongoDB instance

Run the following command in the admin database:

db.getCollection("system.users").find()
Note

You can run this command without modification.

The response looks like the following:

{ "_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 database accounts in a target database

Note

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

  • Method 1: Run the query command in the target database.

    show users
    Note

    You can run this command without modification.

    The response looks like the following:

    {
            "_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 query command in the admin database.

    Syntax:

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

    Parameter description: database_name specifies the name of the target database.

    Example:

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

    The response looks like the following:

    { "_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 single database account in a target database

Note

The command to query a single database account must be run in the admin database.

Syntax:

db.getCollection("system.users").find({user: "user_name", db: "database_name"})

Parameter description:

  • user_name: specifies the name of the database account.

  • database_name: specifies the name of the database to which the account belongs.

Example:

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

The response looks like the following:

{ "_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

Database

Role

Description

All databases

readOnly

Grants read-only permissions on the database.

readWrite

Grants read and write permissions on the database.

userAdmin

Grants permissions to create accounts and roles in the database.

dbAdmin

Grants permissions to manage collections in the database.

dbOwner

Includes all permissions of readWrite, userAdmin, and dbAdmin.

enableSharding

Allows a database in a sharded cluster instance to be sharded across multiple shards.

admin database

readAnyDatabase

Grants read-only permissions on all databases.

readWriteAnyDatabase

Grants read and write permissions on all databases.

userAdminAnyDatabase

Grants permissions to create accounts and roles in all databases.

dbAdminAnyDatabase

Grants permissions to manage collections in all databases.

clusterMonitor

Grants permissions to run information-gathering commands.

hostManager

Grants permissions to run commands such as setParameter, killop, resync, and killCursors.

clusterManager

Grants permissions to run node management commands.

clusterAdmin

Includes all permissions of clusterMonitor, hostManager, and clusterManager.

root

Includes all permissions in the admin database, such as readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase.

Note

For more information about roles, see Built-In Roles.

References