All Products
Search
Document Center

ApsaraDB for MongoDB:Use the mongo shell to manage database accounts

Last Updated:Mar 29, 2024

The mongo shell is a database management tool provided by ApsaraDB for MongoDB. ApsaraDB for MongoDB allows you to manage database accounts by using the mongo shell. This topic describes how to use the mongo shell to create and query database accounts.

Prerequisites

  1. An ApsaraDB for MongoDB instance is created. The methods that you can use to create an instance vary based on the instance architecture. For more information, see the following topics:

  2. The instance is connected by using the mongo shell. Connection methods vary based on the instance architecture. For more information, see the following topics:

Precautions

Database accounts must be unique within a database.

Create a database account

Note
  • Database accounts created by using the mongo shell are not listed on the Accounts page of the ApsaraDB for MongoDB console.

  • The first time you use the mongo shell to create a database account, you must authenticate the root account of the instance in the admin database.

  1. Switch to the admin database.

    use admin
    Note

    This command can be used without any changes.

  2. Authenticate the root account.

    Syntax:

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

    password indicates the password of the root account.

    Example:

    db.auth("root","123456Aa")
  3. Create a database account.

    • Method 1: Switch to a specific database and create an account in the database.

      A database account belongs to the database in which the account is created. You can switch databases by using the use database_name command.

      Syntax:

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

      The following table describes the parameters used in the syntax.

      Parameter

      Description

      Example

      user_name

      The name of the database account.

      If the name contains specific special characters, they must be percent-encoded. These special characters include : / ? # [ ] @. For more information, see Percent-Encoding.

      test

      password

      The password of the database account.

      123456Aa

      role_name

      The role assigned to the database account.

      For more information, see the "Roles of database accounts" section of this topic.

      readAnyDatabase

      role_database_name

      The database in which the role is created.

      For example, {role: "readAnyDatabase", db: "admin"} specifies to assign the readAnyDatabase role to the account of the admin database. In this case, the account has read-only permissions on all databases in the instance.

      admin

      Example:

      Create an account named "test" in the admin database, set the account password to 123456Aa, and assign the readAnyDatabase role to the account.

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

      If the account creation is successful, the following result is returned:

      Successfully added user: {
              "user" : "test",
              "roles" : [
                      {
                              "role" : "readAnyDatabase",
                              "db" : "admin"
                      }
              ]
      }
    • Method 2: Create a database account without switching databases.

      You can run one of the following commands to create a database account:

      • Command 1:

        Syntax:

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

        The following table describes the parameters used in the syntax.

        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 name contains specific special characters, they must be percent-encoded. These special characters include : / ? # [ ] @. For more information, see Percent-Encoding.

        test

        password

        The password of the database account.

        123456Aa

        role_name

        The role assigned to the database account.

        For more information, see the "Roles of database accounts" section of this topic.

        readAnyDatabase

        role_database_name

        The database in which the role is created.

        For example, {role: "readAnyDatabase", db: "admin"} specifies to assign the readAnyDatabase role to the account of the admin database. In this case, the account has read-only permissions on all databases in the instance.

        admin

        Example:

        Create an account named "test" in the admin database, set the account password to 123456Aa, and assign the readAnyDatabase role to the account.

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

        If the account creation is successful, the following result is returned:

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

        Syntax:

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

        The following table describes the parameters used in the syntax.

        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 name contains specific special characters, they must be percent-encoded. These special characters include : / ? # [ ] @. For more information, see Percent-Encoding.

        test

        password

        The password of the database account.

        123456Aa

        role_name

        The role assigned to the database account.

        For more information, see the "Roles of database accounts" section of this topic.

        readAnyDatabase

        role_database_name

        The database in which the role is created.

        For example, {role: "readAnyDatabase", db: "admin"} specifies to assign the readAnyDatabase role to the account of the admin database. In this case, the account has read-only permissions on all databases in the instance.

        admin

        Example:

        Create an account named "test" in the admin database, set the account password to 123456Aa, and assign the readAnyDatabase role to the account.

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

        If the account creation is successful, the following result is returned:

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

Query database accounts

To query all database accounts that belong to an instance, use the following method:

Run the following command:

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

This command can be used without any changes.

The following result is returned:

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

To query all database accounts that belong to a specific database, use one of the following methods:

Note

You can switch databases by using the use database_name command.

  • Method 1: Run a query command in the database

    show users
    Note

    This command can be used without any changes.

    The following result is returned:

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

    Syntax:

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

    database_name indicates the name of the database for which you want to query an account.

    Example:

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

    The following result is returned:

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

To query a single database account that belongs to a specific database, use the following method:

Note

The command that is used 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"})

Parameters

  • user_name: the name of the database account.

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

Example:

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

The following result is returned:

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

Allows the user to create accounts and roles in the database.

dbAdmin

Allows the user to manage collections in the database.

dbOwner

Contains permissions granted by readWrite, userAdmin, and dbAdmin.

enableSharding

Allows the user to enable or disable cross-shard distribution of databases in a sharded cluster instance.

admin database

readAnyDatabase

Grants read-only permissions on all databases.

readWriteAnyDatabase

Grants read and write permissions on all databases.

userAdminAnyDatabase

Allows the user to create accounts and roles in all databases.

dbAdminAnyDatabase

Allows the user to manage collections in all databases.

clusterMonitor

Allows the user to run commands that query database performance information.

hostManager

Allows the user to run the setParameter, killop, resync, and killCursors commands.

clusterManager

Allows the user to manage nodes.

clusterAdmin

Contains permissions granted by clusterMonitor, hostManager, and clusterManager.

root

Contains permissions granted by all roles that are available to the admin database, such as readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase.

Note

For more information, see Built-In Roles.

References