显示目录

MongoDB 账号密码登录

配置MongoDB 账号密码登录的步骤如下 (假设有 2 个数据库 admin (自带的) 和 foo):

  1. 启动 MongoDB: mongod --config /usr/local/etc/mongod.conf

  2. 进入数据库 admin: use admin

  3. 创建用户 admin:

    1
    2
    3
    4
    5
    6
    7
    db.createUser(
    {
    user: "admin",
    pwd: "ebag",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
    }
    )
  4. 进入数据库 foo: use foo

  5. 创建用户 bar:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    db.createUser(
    {
    user: "bar",
    pwd: "bar",
    roles: [
    { role: "dbAdmin", db: "foo" },
    { role: "readWrite", db: "foo" }
    ]
    }
    )
  6. 需要授权的方式启动: mongod --auth --config /usr/local/etc/mongod.conf

  7. 授权登录

    • 方式一: mongo 先进入然后 db.auth("bar", "bar") 授权
    • 方式二: mongo --port 27017 -u "bar" -p "bar" --authenticationDatabase "foo"