Mongodb - Beginner

Page content

Some Hands’on with MongoDB

Run via Docker

docker run -d mongo

Install macOS

brew install mongodb-community

To start mongodb/brew/mongodb-community now and restart at login:

brew services start mongodb/brew/mongodb-community

Or, if you don’t want/need a background service you can just run:

mongod --config /usr/local/etc/mongod.conf

Install OpenBSD

pkg_add mongodb--%44 mongo-tools--

Tune OpenFiles

cat <<'EOF'>> /etc/login.conf

mongod:\
	:openfiles-cur=1024:\
	:openfiles-max=2048:\
	:tc=daemon:
EOF
cap_mkdb /etc/login.conf

-> needs reboot …

Start DB

rcctl enable mongod
rcctl start mongod

connect

mongo
show dbs
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

config File

cat /etc/mongodb.conf

# Sample configuration. See
#   https://docs.mongodb.org/manual/administration/configuration/
# for details.

processManagement:
  fork: true
net:
  bindIp: 127.0.0.1
  port: 27017
storage:
  dbPath: /var/mongodb/data
  journal:
    enabled: true
systemLog:
  destination: file
  path: /var/log/mongodb/mongodb.log
  logAppend: true

So far, so good … but we dont not have and security restrictions except binding the mongod to localhost. Let’s change that add enable user based credentials

Create Admin User

Login and create an Admin User:

  • dbadmin / dbpass
mongo
use admin
db.createUser(
  {
    user: "dbadmin",
    pwd: "dbpass",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
Successfully added user: {
	"user" : "dbadmin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		},
		"readWriteAnyDatabase"
	]
}
> 

Update Config File

enable Security in the mongodb config file

cat << EOF >> /etc/mongodb.conf
security:
  # added: $(date)
  authorization: enabled
EOF

restart DB

rcctl restart mongod

Login without Credentials

mongo
MongoDB shell version v4.4.16
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c5b12250-f0fc-4767-936e-4d6ebebafa8d") }
MongoDB server version: 4.4.16
show dbs
>

-> no more db’s ..

Login with Credentials

mongo --port 27017  --authenticationDatabase "admin" -u "dbadmin" -p "dbpass"
show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Login with Credentials, ask for Password

-> ask for password

mongo --authenticationDatabase "admin" -u "dbadmin" -p

Test DB

Let’s Create a Test DB, RW and RO User and some Sample Data

Create RO/RW User

use test
db.createUser(
  {
    user: "rouser",
    pwd:  "dbpass",
    roles: [ { role: "read", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)
db.createUser(
  {
    user: "rwuser",
    pwd:  "dbpass",
    roles: [ { role: "readWrite", db: "test" },
             { role: "readWrite", db: "reporting" } ]
  }
)
exit

Login with RW User

mongo -u "rwuser" --authenticationDatabase "test" -p "dbpass"

and insert some data

db.foo.insert( { x: 1, y: 1 } )

and find them again

db.foo.find()
{ "_id" : ObjectId("63adadafca872bf706191fa6"), "x" : 1, "y" : 1 }

Login with RO User

mongo -u "rouser" --authenticationDatabase "test" -p "dbpass"

and insert some data

db.foo.insert( { a: 1, rb 1 } )
WriteCommandError({
	"ok" : 0,
	"errmsg" : "not authorized on test to execute command { insert: \"foo\", ordered: true, lsid: { id: UUID(\"2a9776e4-1f16-46c9-bbc5-bc4bf39ce9b0\") }, $db: \"test\" }",
	"code" : 13,
	"codeName" : "Unauthorized"
})

that’s fine, but Read should be possibe …

db.foo.find()
{ "_id" : ObjectId("63adadafca872bf706191fa6"), "x" : 1, "y" : 1 }

Show Users and Permissions

db.getUsers()
[
	{
		"_id" : "test.rouser",
		"userId" : UUID("d7a6a703-81bf-4c4f-861d-3933eec5eb9d"),
		"user" : "rouser",
		"db" : "test",
		"roles" : [
			{
				"role" : "read",
				"db" : "test"
			},
			{
				"role" : "read",
				"db" : "reporting"
			}
		],
		"mechanisms" : [
			"SCRAM-SHA-1",
			"SCRAM-SHA-256"
		]
	},
	{
		"_id" : "test.rwuser",
		"userId" : UUID("e63b739d-b4b4-4000-bfff-e7e81fcc20e3"),
		"user" : "rwuser",
		"db" : "test",
		"roles" : [
			{
				"role" : "readWrite",
				"db" : "test"
			},
			{
				"role" : "readWrite",
				"db" : "reporting"
			}
		],
		"mechanisms" : [
			"SCRAM-SHA-1",
			"SCRAM-SHA-256"
		]
	}
]

DropDB

you wann kill DB: test ?

mongo
show dbs
use test
db.dropDatabase()
exit

Backup Script

How to Backup/Export all Mongo DB’s ?

cat << 'EOF' > mongodb_backup_all.sh
#!/usr/bin/env bash

# Backup all Mongo DB's to a Folder and Compress the Files.
# @stoege, 30.12.2022

# Set Output Directory
FOLDER="mongo_backup"
test -d $FOLDER && rm -rf $FOLDER
mkdir -p $FOLDER
cd $FOLDER

# Set the hostname of the MongoDB server
HOST=localhost

# Get a list of all the databases on the server
DBS=$(mongo --quiet --host $HOST --eval "db.getMongo().getDBNames()" |tr -d '[' |tr -d ']' |tr -d ',' |tr -d '"')

# Loop through the list of databases and create a backup for each one
for DB in $DBS
do

  # Create the backup directory for the current database
  mkdir -p $DB

  # Use mongodump to create a binary export of the database
  mongodump --host $HOST --db $DB --out $DB

  # Compress the backup directory
  tar -zcf $DB.tar.gz $DB

  # Remove the uncompressed backup directory
  rm -r $DB

done

exit 0
EOF

Set Permission and Run

chmod u+x mongodb_backup_all.sh
./mongodb_backup_all.sh

Happy MongoDB !


Any Comments ?

sha256: ee6225d7326bb52da288285294e54f2d6dae14eaa09cf69d2743391a02f138d3