创建 MongoDB 的超级用户的方法

以下是创建MongoDB超级用户的方法。

    在没有认证的情况下,创建用户。
$ mongosh
test> use admin
switched to db admin
admin> db.createUser({user: "scott",pwd: "tiger123",roles: ["userAdminAnyDatabase","readWriteAnyDatabase","dbAdminAnyDatabase"]})
{ ok: 1 }
admin> 
    要启用身份验证,请更改设置并重新启动mongodb。
# 略
auth=true
sudo systemctl restart mongodb
    确认能够登录
$ mongosh admin -u scott -p tiger123
Current Mongosh Log ID:	622420bbd3e3dec28881718d
Connecting to:		mongodb://127.0.0.1:27017/admin?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB:		5.0.6
Using Mongosh:		1.2.2

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting:
   2022-03-06T09:08:46.696+09:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2022-03-06T09:08:48.768+09:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

admin> 

使用脚本创建的方法

db.createUser({user: "scott",pwd: "tiger123",
	roles: ["userAdminAnyDatabase","readWriteAnyDatabase",
	"dbAdminAnyDatabase"]
	})

运行命令

mongosh admin < create_user.js

删除用户

$ mongosh
test> use admin
switched to db admin
admin> db.dropUser('scott')
{ ok: 1 }
admin> 
广告
将在 10 秒后关闭
bannerAds