Installation and basic configuration of MongoDB
MongoDB is a popular NoSQL database known for its flexibility and scalability. Below is a step-by-step guide on setting up a MongoDB environment, from installation to basic configuration, to get started.
Download and Installation
MongoDB offers Community and Enterprise editions, with the Community edition suitable for most development scenarios. Visit the MongoDB official website to download the installation package for your operating system.
Windows Installation Example:
- Run the downloaded
.msi
installer - Select "Complete" for a full installation
- Uncheck "Install MongoDB Compass" (optional GUI tool)
- Click Install to begin the installation
# Linux (Ubuntu) installation command example
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
Service Startup and Shutdown
After installation, the MongoDB service needs to be started. The startup process varies by operating system.
Windows Service Management:
# Start the service
net start MongoDB
# Stop the service
net stop MongoDB
Linux System Service Commands:
# Start the service
sudo systemctl start mongod
# Enable auto-start on boot
sudo systemctl enable mongod
# Check service status
sudo systemctl status mongod
Basic Configuration
The MongoDB configuration file is typically located at /etc/mongod.conf
(Linux) or bin/mongod.cfg
(Windows) in the installation directory. Key configuration items include:
# Example configuration file
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
dbPath: "/var/lib/mongodb"
journal:
enabled: true
net:
port: 27017
bindIp: 127.0.0.1 # In production, restrict access IPs
security:
authorization: enabled # Enable authentication
User and Permission Management
Before enabling authentication, create an admin user:
// Connect to MongoDB
use admin
// Create an admin user
db.createUser({
user: "admin",
pwd: "securepassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
Example of creating a database user:
use mydb
db.createUser({
user: "devuser",
pwd: "devpassword",
roles: [ { role: "readWrite", db: "mydb" } ]
})
Connecting to the Database
After installation and configuration, MongoDB can be accessed in various ways:
Command-Line Connection:
mongo -u devuser -p devpassword --authenticationDatabase mydb
Node.js Connection Example:
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://devuser:devpassword@localhost:27017/mydb?authSource=mydb";
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected successfully to server");
const database = client.db("mydb");
const collection = database.collection("users");
// Example of inserting a document
await collection.insertOne({ name: "Alice", age: 25 });
} finally {
await client.close();
}
}
main().catch(console.error);
Data Directory and Logs
MongoDB requires specified data storage directories and log files:
- Data Directory: Default is
/var/lib/mongodb
on Linux andC:\data\db
on Windows - Log File: Typically located at
/var/log/mongodb/mongod.log
(Linux) orlog/mongod.log
(Windows) in the installation directory
Ensure these directories have proper write permissions:
# Linux permission setup example
sudo mkdir -p /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo mkdir -p /var/log/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodb
Performance Tuning
Adjust MongoDB performance parameters based on server configuration:
# Add performance-related settings to the configuration file
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 2 # Adjust based on server memory; recommended not to exceed 50% of available memory
operationProfiling:
slowOpThresholdMs: 100
mode: slowOp
Backup and Restore
Basic backup and restore operations:
# Backup the entire database
mongodump --uri="mongodb://devuser:devpassword@localhost:27017/mydb" --out=/backup/
# Restore the database
mongorestore --uri="mongodb://devuser:devpassword@localhost:27017/mydb" /backup/mydb/
Troubleshooting Common Issues
Connection Refused:
- Check if the service is running
- Verify firewall settings
- Confirm the
bindIp
configuration is correct
Authentication Failed:
- Ensure the username and password are correct
- Check the authentication database (
authSource
) parameter - Confirm the user has sufficient permissions
Insufficient Disk Space:
// Check database size
db.stats()
// Check collection size
db.collection.stats()
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn