ใช้ db.changeUserPassword() เปลี่ยนรหัสผ่านผู้ใช้
ใน MongoDB 3.0+ สามารถเปลี่ยนรหัสผ่าน User ได้โดยตรงผ่าน Shell โดยไม่ต้องลบและสร้างใหม่
ขั้นตอน: สร้าง User ก่อน (ถ้ายังไม่มี)
> use admin
switched to db admin
> db.createUser({
user: "Chris",
pwd: "chris",
roles: [ { role: "readWrite", db: "test" } ]
});
Successfully added user: { "user" : "Chris", "roles" : [ { "role" : "readWrite", "db" : "test" } ] }
ตรวจสอบ User
> db.getUser("Chris");
{
"_id" : "admin.Chris",
"user" : "Chris",
"db" : "admin",
"roles" : [ { "role" : "readWrite", "db" : "test" } ],
"mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ]
}
คำสั่งเปลี่ยนรหัสผ่าน
> db.changeUserPassword("Chris", "123456");
ผลลัพธ์: รหัสผ่านถูกเปลี่ยนเรียบร้อย (ไม่มี Output ถ้าสำเร็จ)
คำสั่งที่เกี่ยวข้อง
| คำสั่ง | วัตถุประสงค์ |
|---|---|
db.changeUserPassword(username, newPassword) | เปลี่ยนรหัสผ่าน |
db.updateUser(username, { pwd: "newPass", roles: [...] }) | เปลี่ยนรหัสผ่านและ/หรือ Roles พร้อมกัน |
db.dropUser(username) | ลบ User |
db.auth(username, password) | Login ทดสอบรหัสผ่านใหม่ |
หมายเหตุสำคัญ
- ต้องรันในฐานข้อมูล
admin(ที่ User ถูกสร้างไว้) - ต้องมีสิทธิ์
userAdminหรือroot - รหัสผ่านใหม่ควรแข็งแกร่ง: ยาว 12+ ตัวอักษร, ผสมพิมพ์ใหญ่/เล็ก, ตัวเลข, สัญลักษณ์
- ใน Production ควรเปลี่ยนรหัสผ่านเป็นระยะ และใช้ Keyfile/x.509 สำหรับ Cluster