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: databases-43description: PostgreSQL and MongoDB patterns, queries, and optimization. ALWAYS use when the user mentions "SQL", "query", "database", "table", "schema", "migration", "index", "slow query", "Postgres", "Mongo", "base de données", "requête", "optimiser". Provides best practices for schema design, query optimization, indexing strategies, migrations, and performance tuning. Use when writing complex queries, debugging slow performance, designing schemas, or setting up database infrastructure.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# Connection
66mongodb+srv://user:pass@cluster.mongodb.net/db
67
68# Shell
69mongosh "mongodb+srv://cluster.mongodb.net/mydb"
70
71# Basic operations
72db.users.insertOne({ name: "Alice", age: 30 })
73db.users.find({ age: { $gte: 18 } })
74db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
75db.users.deleteOne({ name: "Alice" })
76```
77
78### PostgreSQL Setup
79
80```bash
81# Ubuntu/Debian
82sudo apt-get install postgresql postgresql-contrib
83
84# Start service
85sudo systemctl start postgresql
86
87# Connect
88psql -U postgres -d mydb
89
90# Basic operations
91CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, age INT);
92INSERT INTO users (name, age) VALUES ('Alice', 30);
93SELECT * FROM users WHERE age >= 18;
94UPDATE users SET age = 31 WHERE name = 'Alice';
95DELETE FROM users WHERE name = 'Alice';
96```
97
98## Common Operations
99
100### Create/Insert
101```javascript
102// MongoDB
103db.users.insertOne({ name: "Bob", email: "bob@example.com" })
104db.users.insertMany([{ name: "Alice" }, { name: "Charlie" }])
105```
106
107```sql
108-- PostgreSQL
109INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');
110INSERT INTO users (name, email) VALUES ('Alice', NULL), ('Charlie', NULL);
111```
112
113### Read/Query
114```javascript
115// MongoDB
116db.users.find({ age: { $gte: 18 } })
117db.users.findOne({ email: "bob@example.com" })
118```
119
120```sql
121-- PostgreSQL
122SELECT * FROM users WHERE age >= 18;
123SELECT * FROM users WHERE email = 'bob@example.com' LIMIT 1;
124```
125
126### Update
127```javascript
128// MongoDB
129db.users.updateOne({ name: "Bob" }, { $set: { age: 25 } })
130db.users.updateMany({ status: "pending" }, { $set: { status: "active" } })
131```
132
133```sql
134-- PostgreSQL
135UPDATE users SET age = 25 WHERE name = 'Bob';
136UPDATE users SET status = 'active' WHERE status = 'pending';
137```
138
139### Delete
140```javascript
141// MongoDB
142db.users.deleteOne({ name: "Bob" })
143db.users.deleteMany({ status: "deleted" })
144```
145
146```sql
147-- PostgreSQL
148DELETE FROM users WHERE name = 'Bob';
149DELETE FROM users WHERE status = 'deleted';
150```
151
152### Indexing
153```javascript
154// MongoDB
155db.users.createIndex({ email: 1 })
156db.users.createIndex({ status: 1, createdAt: -1 })
157```
158
159```sql
160-- PostgreSQL
161CREATE INDEX idx_users_email ON users(email);
162CREATE INDEX idx_users_status_created ON users(status, created_at DESC);
163```
164
165## Reference Navigation
166
167### MongoDB References
168- **[mongodb-crud.md](references/mongodb-crud.md)** - CRUD operations, query operators, atomic updates
169- **[mongodb-aggregation.md](references/mongodb-aggregation.md)** - Aggregation pipeline, stages, operators, patterns
170- **[mongodb-indexing.md](references/mongodb-indexing.md)** - Index types, compound indexes, performance optimization
171- **[mongodb-atlas.md](references/mongodb-atlas.md)** - Atlas cloud setup, clusters, monitoring, search
172
173### PostgreSQL References
174- **[postgresql-queries.md](references/postgresql-queries.md)** - SELECT, JOINs, subqueries, CTEs, window functions
175- **[postgresql-psql-cli.md](references/postgresql-psql-cli.md)** - psql commands, meta-commands, scripting
176- **[postgresql-performance.md](references/postgresql-performance.md)** - EXPLAIN, query optimization, vacuum, indexes
177- **[postgresql-administration.md](references/postgresql-administration.md)** - User management, backups, replication, maintenance
178
179## Python Utilities
180
181Database utility scripts in `scripts/`:
182- **db_migrate.py** - Generate and apply migrations for both databases
183- **db_backup.py** - Backup and restore MongoDB and PostgreSQL
184- **db_performance_check.py** - Analyze slow queries and recommend indexes
185
186```bash
187# Generate migration
188python scripts/db_migrate.py --db mongodb --generate "add_user_index"
189
190# Run backup
191python scripts/db_backup.py --db postgres --output /backups/
192
193# Check performance
194python scripts/db_performance_check.py --db mongodb --threshold 100ms
195```
196
197## Key Differences Summary
198
199| Feature | MongoDB | PostgreSQL |
200|---------|---------|------------|
201| Data Model | Document (JSON/BSON) | Relational (Tables/Rows) |
202| Schema | Flexible, dynamic | Strict, predefined |
203| Query Language | MongoDB Query Language | SQL |
204| Joins | $lookup (limited) | Native, optimized |
205| Transactions | Multi-document (4.0+) | Native ACID |
206| Scaling | Horizontal (sharding) | Vertical (primary), Horizontal (extensions) |
207| Indexes | Single, compound, text, geo, etc | B-tree, hash, GiST, GIN, etc |
208
209## Best Practices
210
211**MongoDB:**
212- Use embedded documents for 1-to-few relationships
213- Reference documents for 1-to-many or many-to-many
214- Index frequently queried fields
215- Use aggregation pipeline for complex transformations
216- Enable authentication and TLS in production
217- Use Atlas for managed hosting
218
219**PostgreSQL:**
220- Normalize schema to 3NF, denormalize for performance
221- Use foreign keys for referential integrity
222- Index foreign keys and frequently filtered columns
223- Use EXPLAIN ANALYZE to optimize queries
224- Regular VACUUM and ANALYZE maintenance
225- Connection pooling (pgBouncer) for web apps
226
227## Resources
228
229- MongoDB: https://www.mongodb.com/docs/
230- PostgreSQL: https://www.postgresql.org/docs/
231- MongoDB University: https://learn.mongodb.com/
232- PostgreSQL Tutorial: https://www.postgresqltutorial.com/