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
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:
NoteThe 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
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.
Switch to the admin database.
use admin
NoteThis command can be used without any changes.
Authenticate the root account.
Syntax:
db.auth("root","password")
password
indicates the password of the root account.Example:
db.auth("root","123456Aa")
(Optional) Create a custom database role.
To limit access to a specific collection, create a custom database role, enabling fine-grained access control.
Switch to the desired database: Run the
use database_name
command to switch to the database that you want to access.database_name
indicates the name of the desired database.Specify the role permission ranges: The custom role applies only to the database in which it is created. To apply the role to multiple databases, create it in the
admin
database.
Syntax:
db.createRole({role: "role_name", privileges: [{resource: {db: "role_database_name", collection: "collection_name" }, actions: [ "actions" ] }],roles: []})
Parameters:
Parameter
Description
Example
role_name
The name of the new role.
readRole
role_database_name
The name of the database to which the role belongs. This parameter indicates that the role has permissions on the database to which it belongs.
testDB
collection_name
The name of the collection.
testCollection
actions
The allowed operation type. Example:
find
,insert
,update
, anddelete
.find
roles
Other roles that the new role inherits. An empty array indicates the new role does not inherit other roles, but must contain the
roles
field.[]
NoteFor more information, see db.createRole().
Example:
In this example, a role named readRole is created in a database named testDB, and the find permission on a collection named testCollection in the database is granted to the role.
db.createRole({role: "readRole",privileges: [{resource: {db: "testDB", collection: "testCollection" }, actions: [ "find" ]}],roles: []})
If the role creation is successful, the following result is returned:
{ 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 }) }
Create a database account.
Method 1: Switch to a database and create a database account
A database account belongs to the database in which the account is created.
You can run the
use database_name
command to switch to a database.database_name
indicates the name of the database to which you want to switch.Syntax:
db.createUser({user: "user_name", pwd: "password", roles:[{role: "role_name", db: "role_database_name"}]})
Parameters:
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 Roles of database accounts.
readAnyDatabase
role_database_name
The name of the database to which the role belongs.
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.admin
Example:
In this example, an account named test is created in the admin database, the account password is set to 123456Aa, and the readAnyDatabase role is assigned 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 to a database
You can run one of the following commands to create a database account:
db.getMongo()
Syntax:
db.getMongo().getDB("database_name").createUser({user: "user_name", pwd: "password", roles: [{role: "role_name", db: "role_database_name"}]})
Parameters:
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 Roles of database accounts.
readAnyDatabase
role_database_name
The name of the database to which the role belongs.
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.admin
Example:
In this example, an account named test is created in the admin database, the account password is set to 123456Aa, and the readAnyDatabase role is assigned 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" } ] }
db.getSiblingDB
Syntax:
db.getSiblingDB("database_name").createUser({user: "user_name", pwd: "password", roles: [{role: "role_name", db: "role_database_name"}]})
Parameters:
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 Roles of database accounts.
readAnyDatabase
role_database_name
The name of the database to which the role belongs.
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.admin
Example:
In this example, an account named test is created in the admin database, the account password is set to 123456Aa, and the readAnyDatabase role is assigned 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()
This command can be used without any changes.
The following output 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:
You can switch databases by using the use database_name
command.
Method 1: Run a query command in the database.
show users
NoteThis command can be used without any changes.
The following output 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 output 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:
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 output 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. |
For more information, see Built-In Roles.