Mongo

From bibbleWiki
Jump to navigation Jump to search

Install

This was last done on Ubuntu 24.04

sudo bash
apt-get install gnupg -y

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor


echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

apt-get update 

sudo apt install -y mongodb-org

sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod

Test connection with

mongosh --eval 'db.runCommand({ connectionStatus: 1 })'

Do some stuff to show working

mongosh
use test_db
db.files.insert({"name":"rap"})
db.dropDatabase()

Configure Mongo

Create Admin User

Enter the shell

mongosh

Then use this command changed appropriately

db.createUser({
  user: "new_admin",
  pwd: "not_saying",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } , "readWriteAnyDatabase" ]
})

Then exit shell

exit

Configure Security

sudo vi /etc/mongod.conf

security:
  authorization: enabled

Restart the service

sudo systemctl restart mongod

Create a user

Start the cli interface with

mongo

Now type

use admin
db.createUser({
 user: "Employeeadmin",
 pwd: "password",
 roles:[{role: "userAdmin" , db:"test_db"}]
})
quit()

No test by Test is

mongo -u admin -p --authenticationDatabase admin
use admin
db.getUsers();

Connecting from cli

For admin

mongo -u  admin -p --authenticationDatabase  admin

For normal user

mongo -u  test_admin -p test_admin --host localhost

Create/Show/Delete a database and user

Ezzy pezzy

use mydb
show dbs
db.dropDatabase()

Grant Authority to A Role

Two commands are used

db.auth("user","password")
db.grantRolesToUser( "user", [ { role: "dbOwner", db: "test_db" } ])

Running a container

This is here we ease of use. Don't use this username or password

docker volume create  mongodata
docker run -d --rm --name mongo -p 27017:27017 -v mongodata -e MONGO_INITDB_ROOT_USERNAME=mongo_admin -e  MONGO_INITDB_ROOT_PASSWORD=pass1y### mongo