MongoDB - haiquang9994/dev_env GitHub Wiki

Install MongoDB

https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/

Create root user

use admin

db.createUser({
    user: "root",
    pwd: "1234",
    roles: [
        "userAdminAnyDatabase",
        "dbAdminAnyDatabase",
        "readWriteAnyDatabase",
        "clusterAdmin"
    ]
})

Create normal user

use admin

db.createUser({
    user: "web",
    pwd: "1234",
    roles: [
        {
            "role" : "readWrite",
            "db" : "db_name"
        }
    ]
})

Change password

db.changeUserPassword("web", "1234")

Drop user

db.dropUser("web", {w: "majority", wtimeout: 5000})

Grant roles

use admin

db.grantRolesToUser("web", [
    {
        "role": "readWrite",
        "db": "db_name"
    }
])

Revoke roles

db.revokeRolesFromUser("web", [
    {
        "role": "readWrite",
        "db": "db_name"
    }
])

Enable authentication

Edit mongod.conf
vim /etc/mongod.conf
security:
  authorization: "enabled"

Enable transaction (Cluster Replica Set)

Generate keyfile
openssl rand -base64 756 > /etc/mongodb.keyfile
chmod 0400 /etc/mongodb.keyfile
chown mongodb:mongodb /etc/mongodb.keyfile
Edit mongod.conf
vim /etc/mongod.conf
security:
  keyFile: /etc/mongodb.keyfile

replication:
  replSetName: rs0

BindIP to connect Cluster Replica Set

Check ip
ip addr show
Edit mongod.conf

Example: xxx.xxx.xxx.xxx is ip of host

vim /etc/mongod.conf
net:
  port: 27017
  bindIp: 127.0.0.1,xxx.xxx.xxx.xxx
Initiate replSet
rs.initiate()

KO TẠO USER -> SET IP -> SET KEY -> ENABLE authorization -> enable replication -> rs.initiate

Change connection string
?replicaSet=rs0
Initiate replSet

Change hostname replSet

cfg = rs.conf()
cfg.members[0].host = "xxx.xxx.xxx.xxx:27017"
rs.reconfig(cfg)