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:
An ApsaraDB for MongoDB instance:
An active mongo shell connection to the instance:
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
Switch to the admin database:
use adminAuthenticate 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: []
})| Parameter | Description | Example |
|---|---|---|
role_name | Name of the new role | readRole |
role_database_name | Database the role applies to | testDB |
collection_name | Collection the role applies to | testCollection |
actions | Allowed operations, such as find, insert, update, and remove | find |
roles | Roles 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>" }]
})| Parameter | Description | Example |
|---|---|---|
user_name | Account name | test |
password | Account password | 123456Aa |
role_name | Role to assign. For valid values, see Roles of database accounts | readAnyDatabase |
role_database_name | Database the role belongs to. For example, { role: "readAnyDatabase", db: "admin" } grants read-only access to all databases | admin |
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 theuse database_namecommand to switch databases, wheredatabase_nameis the name of the target database.
Method 1: Switch to the target database and run:
show usersYou 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>" })| Parameter | Description |
|---|---|
user_name | Name of the account |
database_name | Database 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.
| Scope | Role | Description |
|---|---|---|
| All databases | readOnly | Read-only permissions on the database |
| All databases | readWrite | Read and write permissions on the database |
| All databases | userAdmin | Permissions to create accounts and roles in the database |
| All databases | dbAdmin | Permissions to manage collections in the database |
| All databases | dbOwner | All permissions of readWrite, userAdmin, and dbAdmin |
| All databases | enableSharding | Allows a database in a sharded cluster to be distributed across multiple shards |
| admin database | readAnyDatabase | Read-only permissions on all databases |
| admin database | readWriteAnyDatabase | Read and write permissions on all databases |
| admin database | userAdminAnyDatabase | Permissions to create accounts and roles in all databases |
| admin database | dbAdminAnyDatabase | Permissions to manage collections in all databases |
| admin database | clusterMonitor | Permissions to run various commands for collecting information |
| admin database | hostManager | Permissions to run commands such as setParameter, killop, resync, and killCursors |
| admin database | clusterManager | Permissions to run node management commands |
| admin database | clusterAdmin | All permissions of clusterMonitor, hostManager, and clusterManager |
| admin database | root | All admin database permissions, including readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase |