MongoDB User

Required Access

You must have the createUser action on a database to create a new user on that database.
You must have the grantRole action on a role’s database to grant the role to another user.

If you have the userAdmin or
userAdminAnyDatabase role, you have those actions.

Config file

/etc/mondod.conf, /usr/local/etc/mangod.conf(brew)


User operations

Before doing, you need to start mongod

Access mongo

mongod

How to show system user

db.system.users.find()

Create admin user in all

mongo
use admin
db.createUser(
{
  user: 'yoona',
  pwd: "snsd",
  roles:
  [
    {
	   role: "userAdminAnyDatabase",
	   db: "admin"
	}
  ]
})

Check

db.system.users.find()

{ “_id” : “admin.yoona”, “user” : “yoona”, “db” : “admin”, “credentials” : { “MONGODB-CR” : “194be003b1776b5e6d0fce9860dab6aa” }, “roles” : [ { “role” : “userAdminAnyDatabase”, “db” : “admin” } ] }

Access

mongo --port 27017 -u yoona -p snsd --authenticationDatabase admin

Specific database admin

use mydb
db.createUser(
{
  user: 'tktk',
  pwd: "12345",
  roles:
  [
    {
	   role: "userAdmin",
	   db: "mydb"
	}
  ]
})

Root user

use admin
db.createUser(
    {
      user: "username",
      pwd: "password",
      roles: [ "root" ]
    }
)

Check permission

db.auth("tktk","12345")  # 1

db.auth(“use”, “password”)
If the user doesn’t have permission
Error: 18 { ok: 0.0, errmsg: “auth failed”, code: 18 }
0

Create the user in the database with several permission

use reporting
db.createUser(
    {
      user: "reportsUser",
      pwd: "12345678",
      roles: [
         { role: "read", db: "reporting" },
         { role: "read", db: "products" },
         { role: "read", db: "sales" },
         { role: "readWrite", db: "accounts" }
      ]
    }
)

Delete user

Delete system user

use databasename
db.system.users.remove({user: "username"})

databasename is database name
username is user name

Delete user(dropUser

use mydb
db.dropUser("tktk")

mydb is database name
tktk is username

Refs

qiita
mongodb user guide