如何在具有正确角色的现有数据库上创建MongoDB用户?

要在MongoDB中创建新用户,请使用createUser()。以下是查询-

> db.createUser(
...    {
...       user: "John",
...       pwd: "123456",
...       roles: [ { role: "readWrite", db: "test" } ],
...       mechanisms: [ "SCRAM-SHA-256" ]
...    }
... )

这将产生以下输出-

Successfully added user: {
   "user" : "John",
   "roles" : [
      {
         "role" : "readWrite",
         "db" : "test"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-256"
   ]
}

以下是显示所有用户的查询-

> db.getUsers();

这将产生以下输出-

[
   {
      "_id" : "test.John",
      "user" : "John",
      "db" : "test",
      "roles" : [
         {
            "role" : "readWrite",
            "db" : "test"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-256"
      ]
   }
]