MongoDB version: 5, Ubuntu version: 20.04 LTS.
$ sudo su
# apt-get update
# apt-get upgrade
# wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
# echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
# apt-get update
# apt-get install -y mongodb-org
To enable change streams, add the following to mongod.conf
:
# nano /etc/mongod.conf
replication:
replSetName: rs0
To enable remote access:
net:
port: 27017
bindIp: 0.0.0.0
Run the database as a service:
# systemctl enable mongod
# systemctl start mongod
# systemctl status mongod
Enable replication:
# mongosh
> rs.initiate()
Create a new role that disallow deleting documents/dropping collections and databases:
> use admin
> db.createRole({
role: "dbadmin-lite",
privileges: [
{
resource: { db: "", collection: "" },
actions: [
"find", "insert", "update", "changeStream",
"collStats", "dbHash", "dbStats",
"createCollection", "listCollections",
"createIndex", "reIndex", "listIndexes"
]
}
],
roles: []
})
Create a new user:
> db.createUser({ user: "dbadmin", pwd: "*********", roles: ["dbadmin-lite"]})
Create root user:
> db.createUser({ user: "root", pwd: "*********", roles: ["root"]})
Enable authentication:
# cd /etc
# openssl rand -base64 741 > mongodb.key
# chmod 600 mongodb.key
# chown mongodb mongodb.key
# nano /etc/mongod.conf
security:
authorization: enabled
keyFile: /etc/mongodb.key
Enable SSL:
# openssl req -newkey rsa:2048 -nodes -keyout mongodb.pem -x509 -days 36500 -out mongodb.pem -subj "/CN=*"
# chmod 600 mongodb.pem
# chown mongodb mongodb.pem
# nano /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
ssl:
mode: requireSSL
PEMKeyFile: /etc/mongodb.pem
# systemctl restart mongod
# systemctl status mongod
Clear mongosh history:
# echo "" | sudo tee ~/.mongodb/mongosh/mongosh_repl_history