Databases Skill
Unified guide for working with MongoDB (document-oriented) and PostgreSQL (relational) databases. Choose the right database for your use case and master both systems.
When to Use This Skill
Use when:
- Designing database schemas and data models
- Writing queries (SQL or MongoDB query language)
- Building aggregation pipelines or complex joins
- Optimizing indexes and query performance
- Implementing database migrations
- Setting up replication, sharding, or clustering
- Configuring backups and disaster recovery
- Managing database users and permissions
- Analyzing slow queries and performance issues
- Administering production database deployments
Database Selection Guide
Choose MongoDB When:
- Schema flexibility: frequent structure changes, heterogeneous data
- Document-centric: natural JSON/BSON data model
- Horizontal scaling: need to shard across multiple servers
- High write throughput: IoT, logging, real-time analytics
- Nested/hierarchical data: embedded documents preferred
- Rapid prototyping: schema evolution without migrations
Best for: Content management, catalogs, IoT time series, real-time analytics, mobile apps, user profiles
Choose PostgreSQL When:
- Strong consistency: ACID transactions critical
- Complex relationships: many-to-many joins, referential integrity
- SQL requirement: team expertise, reporting tools, BI systems
- Data integrity: strict schema validation, constraints
- Mature ecosystem: extensive tooling, extensions
- Complex queries: window functions, CTEs, analytical workloads
Best for: Financial systems, e-commerce transactions, ERP, CRM, data warehousing, analytics
Both Support:
- JSON/JSONB storage and querying
- Full-text search capabilities
- Geospatial queries and indexing
- Replication and high availability
- ACID transactions (MongoDB 4.0+)
- Strong security features
Quick Start
MongoDB Setup
# Atlas (Cloud) - Recommended
# 1. Sign up at mongodb.com/atlas
# 2. Create M0 free cluster
# 3. Get connection string
# SECURITY WARNING: Never hardcode credentials in connection strings
# Use environment variables instead:
# mongodb+srv://${DB_USERNAME}:${DB_PASSWORD}@cluster.mongodb.net/db
# Or use connection string from MongoDB Atlas without embedding credentials
# Connection (template - replace with env vars)
mongodb+srv://user:pass@cluster.mongodb.net/db
# Shell
mongosh "mongodb+srv://cluster.mongodb.net/mydb"
# Basic operations
db.users.insertOne({ name: "Alice", age: 30 })
db.users.find({ age: { $gte: 18 } })
db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
db.users.deleteOne({ name: "Alice" })
PostgreSQL Setup
# Ubuntu/Debian
sudo apt-get install postgresql postgresql-contrib
# Start service
sudo systemctl start postgresql
# Connect
psql -U postgres -d mydb
# Basic operations
CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, age INT);
INSERT INTO users (name, age) VALUES ('Alice', 30);
SELECT * FROM users WHERE age >= 18;
UPDATE users SET age = 31 WHERE name = 'Alice';
DELETE FROM users WHERE name = 'Alice';
Common Operations
Create/Insert
// MongoDB
db.users.insertOne({ name: "Bob", email: "bob@example.com" })
db.users.insertMany([{ name: "Alice" }, { name: "Charlie" }])
-- PostgreSQL
INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');
INSERT INTO users (name, email) VALUES ('Alice', NULL), ('Charlie', NULL);
Read/Query
// MongoDB
db.users.find({ age: { $gte: 18 } })
db.users.findOne({ email: "bob@example.com" })
-- PostgreSQL
SELECT * FROM users WHERE age >= 18;
SELECT * FROM users WHERE email = 'bob@example.com' LIMIT 1;
Update
// MongoDB
db.users.updateOne({ name: "Bob" }, { $set: { age: 25 } })
db.users.updateMany({ status: "pending" }, { $set: { status: "active" } })
-- PostgreSQL
UPDATE users SET age = 25 WHERE name = 'Bob';
UPDATE users SET status = 'active' WHERE status = 'pending';
Delete
// MongoDB
db.users.deleteOne({ name: "Bob" })
db.users.deleteMany({ status: "deleted" })
-- PostgreSQL
DELETE FROM users WHERE name = 'Bob';
DELETE FROM users WHERE status = 'deleted';
Indexing
// MongoDB
db.users.createIndex({ email: 1 })
db.users.createIndex({ status: 1, createdAt: -1 })
-- PostgreSQL
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_status_created ON users(status, created_at DESC);
Reference Navigation
MongoDB References
- mongodb-crud.md - CRUD operations, query operators, atomic updates
- mongodb-aggregation.md - Aggregation pipeline, stages, operators, patterns
- mongodb-indexing.md - Index types, compound indexes, performance optimization
- mongodb-atlas.md - Atlas cloud setup, clusters, monitoring, search
PostgreSQL References
- postgresql-queries.md - SELECT, JOINs, subqueries, CTEs, window functions
- postgresql-psql-cli.md - psql commands, meta-commands, scripting
- postgresql-performance.md - EXPLAIN, query optimization, vacuum, indexes
- postgresql-administration.md - User management, backups, replication, maintenance
Python Utilities
Database utility scripts in scripts/:
- db_migrate.py - Generate and apply migrations for both databases
- db_backup.py - Backup and restore MongoDB and PostgreSQL
- db_performance_check.py - Analyze slow queries and recommend indexes
# Generate migration
python scripts/db_migrate.py --db mongodb --generate "add_user_index"
# Run backup
python scripts/db_backup.py --db postgres --output /backups/
# Check performance
python scripts/db_performance_check.py --db mongodb --threshold 100ms
Key Differences Summary
| Feature |
MongoDB |
PostgreSQL |
| Data Model |
Document (JSON/BSON) |
Relational (Tables/Rows) |
| Schema |
Flexible, dynamic |
Strict, predefined |
| Query Language |
MongoDB Query Language |
SQL |
| Joins |
$lookup (limited) |
Native, optimized |
| Transactions |
Multi-document (4.0+) |
Native ACID |
| Scaling |
Horizontal (sharding) |
Vertical (primary), Horizontal (extensions) |
| Indexes |
Single, compound, text, geo, etc |
B-tree, hash, GiST, GIN, etc |
Best Practices
MongoDB:
- Use embedded documents for 1-to-few relationships
- Reference documents for 1-to-many or many-to-many
- Index frequently queried fields
- Use aggregation pipeline for complex transformations
- Enable authentication and TLS in production
- Use Atlas for managed hosting
PostgreSQL:
- Normalize schema to 3NF, denormalize for performance
- Use foreign keys for referential integrity
- Index foreign keys and frequently filtered columns
- Use EXPLAIN ANALYZE to optimize queries
- Regular VACUUM and ANALYZE maintenance
- Connection pooling (pgBouncer) for web apps
Resources
1---2name: databases-33description: Work with MongoDB (document database, BSON documents, aggregation pipelines, Atlas cloud) and PostgreSQL (relational database, SQL queries, psql CLI, pgAdmin). Use when designing database schemas, writing queries and aggregations, optimizing indexes for performance, performing database migrations, configuring replication and sharding, implementing backup and restore strategies, managing database users and permissions, analyzing query performance, or administering production databases.4license: MIT5---6
7# Databases Skill
8
9Unified guide for working with MongoDB (document-oriented) and PostgreSQL (relational) databases. Choose the right database for your use case and master both systems.
10
11## When to Use This Skill
12
13Use when:
14- Designing database schemas and data models
15- Writing queries (SQL or MongoDB query language)
16- Building aggregation pipelines or complex joins
17- Optimizing indexes and query performance
18- Implementing database migrations
19- Setting up replication, sharding, or clustering
20- Configuring backups and disaster recovery
21- Managing database users and permissions
22- Analyzing slow queries and performance issues
23- Administering production database deployments
24
25## Database Selection Guide
26
27### Choose MongoDB When:
28- Schema flexibility: frequent structure changes, heterogeneous data
29- Document-centric: natural JSON/BSON data model
30- Horizontal scaling: need to shard across multiple servers
31- High write throughput: IoT, logging, real-time analytics
32- Nested/hierarchical data: embedded documents preferred
33- Rapid prototyping: schema evolution without migrations
34
35**Best for:** Content management, catalogs, IoT time series, real-time analytics, mobile apps, user profiles
36
37### Choose PostgreSQL When:
38- Strong consistency: ACID transactions critical
39- Complex relationships: many-to-many joins, referential integrity
40- SQL requirement: team expertise, reporting tools, BI systems
41- Data integrity: strict schema validation, constraints
42- Mature ecosystem: extensive tooling, extensions
43- Complex queries: window functions, CTEs, analytical workloads
44
45**Best for:** Financial systems, e-commerce transactions, ERP, CRM, data warehousing, analytics
46
47### Both Support:
48- JSON/JSONB storage and querying
49- Full-text search capabilities
50- Geospatial queries and indexing
51- Replication and high availability
52- ACID transactions (MongoDB 4.0+)
53- Strong security features
54
55## Quick Start
56
57### MongoDB Setup
58
59```bash
60# Atlas (Cloud) - Recommended
61# 1. Sign up at mongodb.com/atlas
62# 2. Create M0 free cluster
63# 3. Get connection string
64
65# SECURITY WARNING: Never hardcode credentials in connection strings
66# Use environment variables instead:
67# mongodb+srv://${DB_USERNAME}:${DB_PASSWORD}@cluster.mongodb.net/db
68# Or use connection string from MongoDB Atlas without embedding credentials
69
70# Connection (template - replace with env vars)
71mongodb+srv://user:pass@cluster.mongodb.net/db
72
73# Shell
74mongosh "mongodb+srv://cluster.mongodb.net/mydb"
75
76# Basic operations
77db.users.insertOne({ name: "Alice", age: 30 })
78db.users.find({ age: { $gte: 18 } })
79db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
80db.users.deleteOne({ name: "Alice" })
81```
82
83### PostgreSQL Setup
84
85```bash
86# Ubuntu/Debian
87sudo apt-get install postgresql postgresql-contrib
88
89# Start service
90sudo systemctl start postgresql
91
92# Connect
93psql -U postgres -d mydb
94
95# Basic operations
96CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, age INT);
97INSERT INTO users (name, age) VALUES ('Alice', 30);
98SELECT * FROM users WHERE age >= 18;
99UPDATE users SET age = 31 WHERE name = 'Alice';
100DELETE FROM users WHERE name = 'Alice';
101```
102
103## Common Operations
104
105### Create/Insert
106```javascript
107// MongoDB
108db.users.insertOne({ name: "Bob", email: "bob@example.com" })
109db.users.insertMany([{ name: "Alice" }, { name: "Charlie" }])
110```
111
112```sql
113-- PostgreSQL
114INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');
115INSERT INTO users (name, email) VALUES ('Alice', NULL), ('Charlie', NULL);
116```
117
118### Read/Query
119```javascript
120// MongoDB
121db.users.find({ age: { $gte: 18 } })
122db.users.findOne({ email: "bob@example.com" })
123```
124
125```sql
126-- PostgreSQL
127SELECT * FROM users WHERE age >= 18;
128SELECT * FROM users WHERE email = 'bob@example.com' LIMIT 1;
129```
130
131### Update
132```javascript
133// MongoDB
134db.users.updateOne({ name: "Bob" }, { $set: { age: 25 } })
135db.users.updateMany({ status: "pending" }, { $set: { status: "active" } })
136```
137
138```sql
139-- PostgreSQL
140UPDATE users SET age = 25 WHERE name = 'Bob';
141UPDATE users SET status = 'active' WHERE status = 'pending';
142```
143
144### Delete
145```javascript
146// MongoDB
147db.users.deleteOne({ name: "Bob" })
148db.users.deleteMany({ status: "deleted" })
149```
150
151```sql
152-- PostgreSQL
153DELETE FROM users WHERE name = 'Bob';
154DELETE FROM users WHERE status = 'deleted';
155```
156
157### Indexing
158```javascript
159// MongoDB
160db.users.createIndex({ email: 1 })
161db.users.createIndex({ status: 1, createdAt: -1 })
162```
163
164```sql
165-- PostgreSQL
166CREATE INDEX idx_users_email ON users(email);
167CREATE INDEX idx_users_status_created ON users(status, created_at DESC);
168```
169
170## Reference Navigation
171
172### MongoDB References
173- **[mongodb-crud.md](references/mongodb-crud.md)** - CRUD operations, query operators, atomic updates
174- **[mongodb-aggregation.md](references/mongodb-aggregation.md)** - Aggregation pipeline, stages, operators, patterns
175- **[mongodb-indexing.md](references/mongodb-indexing.md)** - Index types, compound indexes, performance optimization
176- **[mongodb-atlas.md](references/mongodb-atlas.md)** - Atlas cloud setup, clusters, monitoring, search
177
178### PostgreSQL References
179- **[postgresql-queries.md](references/postgresql-queries.md)** - SELECT, JOINs, subqueries, CTEs, window functions
180- **[postgresql-psql-cli.md](references/postgresql-psql-cli.md)** - psql commands, meta-commands, scripting
181- **[postgresql-performance.md](references/postgresql-performance.md)** - EXPLAIN, query optimization, vacuum, indexes
182- **[postgresql-administration.md](references/postgresql-administration.md)** - User management, backups, replication, maintenance
183
184## Python Utilities
185
186Database utility scripts in `scripts/`:
187- **db_migrate.py** - Generate and apply migrations for both databases
188- **db_backup.py** - Backup and restore MongoDB and PostgreSQL
189- **db_performance_check.py** - Analyze slow queries and recommend indexes
190
191```bash
192# Generate migration
193python scripts/db_migrate.py --db mongodb --generate "add_user_index"
194
195# Run backup
196python scripts/db_backup.py --db postgres --output /backups/
197
198# Check performance
199python scripts/db_performance_check.py --db mongodb --threshold 100ms
200```
201
202## Key Differences Summary
203
204| Feature | MongoDB | PostgreSQL |
205|---------|---------|------------|
206| Data Model | Document (JSON/BSON) | Relational (Tables/Rows) |
207| Schema | Flexible, dynamic | Strict, predefined |
208| Query Language | MongoDB Query Language | SQL |
209| Joins | $lookup (limited) | Native, optimized |
210| Transactions | Multi-document (4.0+) | Native ACID |
211| Scaling | Horizontal (sharding) | Vertical (primary), Horizontal (extensions) |
212| Indexes | Single, compound, text, geo, etc | B-tree, hash, GiST, GIN, etc |
213
214## Best Practices
215
216**MongoDB:**
217- Use embedded documents for 1-to-few relationships
218- Reference documents for 1-to-many or many-to-many
219- Index frequently queried fields
220- Use aggregation pipeline for complex transformations
221- Enable authentication and TLS in production
222- Use Atlas for managed hosting
223
224**PostgreSQL:**
225- Normalize schema to 3NF, denormalize for performance
226- Use foreign keys for referential integrity
227- Index foreign keys and frequently filtered columns
228- Use EXPLAIN ANALYZE to optimize queries
229- Regular VACUUM and ANALYZE maintenance
230- Connection pooling (pgBouncer) for web apps
231
232## Resources
233
234- MongoDB: https://www.mongodb.com/docs/
235- PostgreSQL: https://www.postgresql.org/docs/
236- MongoDB University: https://learn.mongodb.com/
237- PostgreSQL Tutorial: https://www.postgresqltutorial.com/