skip to content

Search

Syspirit
EN

MongoDB

MongoDB Database: NoSQL, documents and collections!

Databases
Published on

MongoDB is a document-oriented NoSQL database that stores data in JSON format (BSON) within flexible collections.

🤔 Why MongoDB?

MongoDB is for:

  • 📄 JSON data - Store JSON directly like in JavaScript
  • 🚀 Rapid development - No need to create tables in advance
  • 🔄 Flexible structure - Data can change shape
  • Simple - Closer to programming

Use it for:

  • REST APIs (JSON data)
  • Mobile applications
  • Storing logs, events
  • Quick prototypes
  • When data doesn’t fit in a spreadsheet

🚀 Installation

📌 System🧠 Command
🐧 Ubuntu/Debiansudo apt install mongodb-server mongodb-clients
🎩 CentOS/RHELsudo yum install mongodb-org
🍎 macOS (Homebrew)brew install mongodb-community
🐳 Dockerdocker run -d mongo:7
🏢 Official versionmongodb.com/try/download

⚙️ Basic Configuration

📌 Action🧠 Command
▶️ Start MongoDBsudo systemctl start mongod
🔄 Enable at bootsudo systemctl enable mongod
🔗 Connectmongosh (or mongo)
📋 View databasesshow dbs
🔗 Use a databaseuse myapp
🚪 Exit mongoshquit() (or Ctrl+C)

🗄️ Database Management

📌 Action🧠 Command
📋 List databasesshow dbs
🆕 Create/use a databaseuse myapp
📊 Current databasedb.getName()
🗑️ Delete current databasedb.dropDatabase()
📊 Database statisticsdb.stats()
💾 Database sizedb.stats().dataSize

📋 Collection Management

📌 Action🧠 Command
📋 List collectionsshow collections
🆕 Create a collectiondb.createCollection("users")
🗑️ Delete a collectiondb.users.drop()
📊 Collection statisticsdb.users.stats()
📖 Count documentsdb.users.countDocuments()
🔍 First documentdb.users.findOne()

👥 User Management

📌 Action🧠 Command
👤 Create an admindb.createUser({user:"admin", pwd:"password", roles:["root"]})
👤 Create read-only userdb.createUser({user:"reader", pwd:"pwd", roles:["read"]})
👤 Create read/write userdb.createUser({user:"editor", pwd:"pwd", roles:["readWrite"]})
📋 List usersdb.getUsers()
🗑️ Delete a userdb.dropUser("reader")
🔐 Enable authenticationEdit /etc/mongod.conf: security.authorization: enabled

💾 Backup and Restore

📌 Action🧠 Command
💾 Backup a databasemongodump --db myapp --out ./backup/
💾 Backup everythingmongodump --out ./backup/
📥 Restore a databasemongorestore --db myapp ./backup/myapp/
📥 Restore everythingmongorestore ./backup/
🗜️ Export JSONmongoexport --db myapp --collection users --out users.json
📦 Import JSONmongoimport --db myapp --collection users --file users.json

🔍 Monitoring and Debug

📌 Action🧠 Command
📊 Server statusdb.serverStatus()
🔗 Active connectionsdb.serverStatus().connections
🐌 Profiler (slow queries)db.setProfilingLevel(2)
📈 View profiledb.system.profile.find()
💾 Memory usagedb.serverStatus().mem
🔧 Current operationsdb.currentOp()