Để liệt kê tất cả users trong MongoDB shell, bạn có 2 cách chính: dùng phương thức db.getUsers() hoặc lệnh show users.
Cách 1: Sử dụng db.getUsers()
db.getUsers();
Cách 2: Sử dụng show command
show users;
Ví dụ minh họa
Cách 1: db.getUsers()
> db.getUsers();
[
{
"_id" : "test.John",
"user" : "John",
"db" : "test",
"roles" : [
{ "role" : "readWrite", "db" : "test" },
{ "role" : "dbAdmin", "db" : "test" }
],
"mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ]
},
{
"_id" : "test.admin",
"user" : "admin",
"db" : "test",
"roles" : [
{ "role" : "root", "db" : "admin" }
],
"mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ]
}
]
Cách 2: show users
> show users;
{
"_id" : "test.John",
"user" : "John",
"db" : "test",
"roles" : [
{ "role" : "readWrite", "db" : "test" },
{ "role" : "dbAdmin", "db" : "test" }
],
"mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ]
}
{
"_id" : "test.admin",
"user" : "admin",
"db" : "test",
"roles" : [
{ "role" : "root", "db" : "admin" }
],
"mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ]
}
So sánh 2 cách
| Đặc điểm | db.getUsers() | show users |
|---|---|---|
| Định dạng output | Array (JSON) | Multiple documents |
| Dễ parse programmatically | Có | Khó hơn |
| Độ đọc cho người | Tốt | Tốt |
| Hỗ trợ trong script | Có | Không (chỉ shell) |
Giải thích các trường user
_id: Unique identifier dạngdatabase.usernameuser: Tên usernamedb: Authentication database (database chứa user)roles: Mảng các role gán cho usermechanisms: Authentication mechanisms hỗ trợ (SCRAM-SHA-1, SCRAM-SHA-256)
Lệnh quản lý user liên quan
// Tạo user
db.createUser({user: "myUser", pwd: "password", roles: ["readWrite"]})
// Xóa user
db.dropUser("myUser")
// Cập nhật user
db.updateUser("myUser", {roles: ["dbAdmin"]})
// Xem role của user hiện tại
db.runCommand({connectionStatus: 1})
Lưu ý: Cần quyền
listUsers hoặc userAdmin để chạy các lệnh này. Mặc định user tạo ra có quyền trên database authentication database của họ.