The mongo shell is a database management tool included with MongoDB. This topic describes how to use the mongo shell to create and query database accounts in ApsaraDB for MongoDB.
Prerequisites
You have created an ApsaraDB for MongoDB instance. For more information about how to create different types of instances, see the following topics:
You have connected to the ApsaraDB for MongoDB instance 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
Database accounts that are created using the mongo shell cannot be queried 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.
Switch to the admin database.
use adminNoteYou can run this command without modification.
Authenticate the root account.
Syntax:
db.auth("root","password")Parameter description:
passwordspecifies the password of the root account.Example:
db.auth("root","123456Aa")(Optional) Create a custom database role.
To restrict access to a specific collection, you can create a custom database role to implement fine-grained access control.
Switch databases: Run the
use database_namecommand to switch to the target database, wheredatabase_nameis 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
admindatabase.
Syntax:
db.createRole({role: "role_name", privileges: [{resource: {db: "role_database_name", collection: "collection_name" }, actions: [ "actions" ] }],roles: []})Parameter description:
Parameter
Description
Example
role_nameThe name of the new role.
readRole
role_database_nameThe name of the database to which the role belongs.
This parameter specifies that the role has operation permissions on the specified database.
testDB
collection_nameThe name of the collection.
testCollection
actionsThe allowed operation types, such as
find,insert,update, andremove.find
rolesOther roles that this role inherits. An empty array indicates that this role does not inherit other roles, but the
rolesfield must be included.[]
NoteFor 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 is returned as shown below:
{ 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 the target database to create an account
A database account belongs to the database in which it is created.
Run the
use database_namecommand to switch to a database, wheredatabase_nameis 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_nameThe 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
passwordThe password of the database account.
123456Aa
role_nameThe role to grant to the database account.
For more information about the valid values, see Roles of database accounts.
readAnyDatabase
role_database_nameThe 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 is returned as shown below:
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 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"}]})Parameter description:
Parameter
Description
Example
database_nameThe name of the database to which the account belongs.
admin
user_nameThe 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
passwordThe password of the database account.
123456Aa
role_nameThe role to grant to the database account.
For more information about the valid values, see Roles of database accounts.
readAnyDatabase
role_database_nameThe 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 is returned as shown below:
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_nameThe name of the database to which the account belongs.
admin
user_nameThe 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
passwordThe password of the database account.
123456Aa
role_nameThe role to grant to the database account.
For more information about the valid values, see Roles of database accounts.
readAnyDatabase
role_database_nameThe 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 is returned as shown below:
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()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 database accounts in a target database
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 usersNoteYou 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 query command in the admin database.
Syntax:
db.getCollection("system.users").find({db: "database_name"})Parameter description:
database_namespecifies the name of the target database.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 single database account in a target database
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 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
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 distributed 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 various commands for collecting information. | |
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. |
For more information about roles, see Built-In Roles.