Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách liệt kê tất cả users trong Mongo Shell

Để 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ểmdb.getUsers()show users
Định dạng outputArray (JSON)Multiple documents
Dễ parse programmaticallyCóKhó hơn
Độ đọc cho ngườiTốtTốt
Hỗ trợ trong scriptCóKhông (chỉ shell)

Giải thích các trường user

  • _id: Unique identifier dạng database.username
  • user: Tên username
  • db: Authentication database (database chứa user)
  • roles: Mảng các role gán cho user
  • mechanisms: 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ọ.