This guide covers essential MongoDB development tools commonly asked in technical interviews. Each question includes detailed answers and practical examples.
Key MongoDB development tools include:
MongoDB Shell usage for development:
// Connect to MongoDB
mongosh "mongodb://localhost:27017/myDatabase"
// Switch database
use myDatabase
// Create collection
db.createCollection("users")
// Insert document
db.users.insertOne({
name: "John Doe",
email: "john@example.com",
age: 30
})
// Query documents
db.users.find({ age: { $gt: 25 } })
// Update document
db.users.updateOne(
{ email: "john@example.com" },
{ $set: { age: 31 } }
)
// Delete document
db.users.deleteOne({ email: "john@example.com" })
// Aggregation pipeline
db.users.aggregate([
{
$match: { age: { $gt: 25 } }
},
{
$group: {
_id: "$status",
count: { $sum: 1 },
avgAge: { $avg: "$age" }
}
}
])
// Create index
db.users.createIndex({ email: 1 }, { unique: true })
// Explain query
db.users.find({ age: { $gt: 25 } }).explain("executionStats")
// Backup database
mongodump --db myDatabase --out /backup
// Restore database
mongorestore --db myDatabase /backup/myDatabase
MongoDB Drivers implementation:
// Connect to MongoDB
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const database = client.db("myDatabase");
const collection = database.collection("users");
// Insert document
const result = await collection.insertOne({
name: "John Doe",
email: "john@example.com",
age: 30
});
// Query documents
const users = await collection.find({ age: { $gt: 25 } }).toArray();
// Update document
await collection.updateOne(
{ email: "john@example.com" },
{ $set: { age: 31 } }
);
// Delete document
await collection.deleteOne({ email: "john@example.com" });
} finally {
await client.close();
}
}
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['myDatabase']
collection = db['users']
# Insert document
result = collection.insert_one({
'name': 'John Doe',
'email': 'john@example.com',
'age': 30
})
# Query documents
users = collection.find({'age': {'$gt': 25}})
# Update document
collection.update_one(
{'email': 'john@example.com'},
{'$set': {'age': 31}}
)
# Delete document
collection.delete_one({'email': 'john@example.com'})
MongoDB Tools for maintenance:
# Backup entire database
mongodump --db myDatabase --out /backup
# Backup specific collection
mongodump --db myDatabase --collection users --out /backup
# Restore database
mongorestore --db myDatabase /backup/myDatabase
# Restore specific collection
mongorestore --db myDatabase --collection users /backup/myDatabase/users.bson
# Export to JSON
mongoexport --db myDatabase --collection users --out users.json
# Import from JSON
mongoimport --db myDatabase --collection users --file users.json
# Check database status
mongostat --host localhost:27017
# Monitor operations
mongotop --host localhost:27017
# Repair database
mongod --repair --dbpath /data/db
# Validate collection
mongosh --eval "db.users.validate()"
# Compact collection
mongosh --eval "db.runCommand({ compact: 'users' })"
# Check database size
mongosh --eval "db.stats()"
Follow these best practices:
# Use version control
git init
git add .
git commit -m "Initial commit"
# Use environment variables
export MONGODB_URI="mongodb://localhost:27017"
export MONGODB_DB="myDatabase"
# Use connection pooling
const client = new MongoClient(uri, {
maxPoolSize: 50,
minPoolSize: 10,
maxIdleTimeMS: 30000
});
# Implement error handling
try {
await client.connect();
// Database operations
} catch (error) {
console.error('Error:', error);
} finally {
await client.close();
}
# Use authentication
mongosh "mongodb://user:password@localhost:27017"
# Enable SSL/TLS
mongosh "mongodb://localhost:27017/?ssl=true"
# Implement connection retry
const client = new MongoClient(uri, {
retryWrites: true,
retryReads: true,
maxRetries: 3
});
# Use proper indexing
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ age: 1, status: 1 })
# Monitor performance
db.currentOp()
db.serverStatus()