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