Skip to content

MongoDB

Erik Palencik edited this page Oct 16, 2026 · 17 revisions

Installation

Linux (Ubuntu)

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

# Activation of certificate 

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.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.2.list

# Installation 
sudo apt install -y mongodb-org
mongod --version

sudo systemctl start mongod
sudo systemctl enable mongod
sudy systemctl status mongo

Error handling linux

Getting full logs

sudo journalctl -u mongod -n 30 --no-pager -l
sudo tail -n 30 /var/log/mongodb/mongod.log

Socket file failure error code 14

sudo rm /tmp/mongodb-27017.sock
sudo chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb
sudo systemctl start mongod
sudo systemctl status mongod

Backup management

Mongo store

This is for Azure Cosmos MongoDB

mongorestore --uri="mongodb+srv://<USERNAME>:<PASSWORD>@<MONGOURL>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000" ./<DATABASE_NAME>

This is for local

mongorestore --uri="mongodb://localhost:27017/" ./<FolderWithDbFolders>

GZIP archive

 mongorestore --uri="mongodb://localhost:27017" --archive=./<FILENAME>.archive --nsFrom="<OLD_DB>.*" --nsTo="<NEW_DB>.*" --gzip

Mongo dump

mongodump --uri="mongodb+srv://<USERNAME>:<PASSWORD>@<MONGOURL>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000" --db <YOUR_DATABASE_NAME> --out ./<OUTPUT_FOLDER>
mongodump --uri="mongodb://localhost:27017/" --db <DB_NAME>--out ./<EXPORT_FOLDER>

Via host:

mongodump --host <MONGOURL>.mongo.cosmos.azure.com:10255 --username <USERNAME> --password <PASSWORD> --ssl --authenticationDatabase admin --db <YOUR_DATABASE_NAME> --out ./<OUTPUT_FOLDER>

Authorization

Edit config file:

security:
  authorization: enabled

With javascript create:

use <DATABASE_NAME>
db.createUser({
  user: "<USER_NAME>",
  pwd: "your-strong-password",
  roles: [ { role: "readWrite", db: "<DATABASE_NAME>" } ]
})

Use connection string:

mongodb://<USER_NAME>:<PASSWORD>@localhost:27017/<DATABASE_NAME>?authSource=<DATABASE_NAME>

Restart the service

Mongo DB ubuntu docker

docker run -d  --name mongodb7  --restart unless-stopped  -p 127.0.0.1:27017:27017  -v mongodb-data7:/data/db mongo:7.0

Usefull tools and commands

Document operations

Rename wrong attribute

For renaming wrong attribute you can use:

db.collection.updateMany(
  {"WRONG_NAME": { $exists: true } },
  { $rename: { "WRONG_NAME": "GOOD_NAME" } }
)

Clone this wiki locally