MongoDB Aggregation Pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| // Complex Analytics Query
db.events.aggregate([
// Filter by date range
{
$match: {
createdAt: {
$gte: ISODate("2024-01-01"),
$lt: ISODate("2024-02-01")
},
type: "page_view"
}
},
// Group by user and page
{
$group: {
_id: {
userId: "$userId",
page: "$page"
},
viewCount: { $sum: 1 },
avgDuration: { $avg: "$duration" }
}
},
// Reshape output
{
$project: {
_id: 0,
userId: "$_id.userId",
page: "$_id.page",
viewCount: 1,
avgDuration: { $round: ["$avgDuration", 2] }
}
},
// Sort by views
{ $sort: { viewCount: -1 } },
// Limit results
{ $limit: 100 }
]);
|
MongoDB Schema Design
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| // Embedded Pattern for User Profile
const userSchema = {
_id: ObjectId,
email: String,
profile: {
firstName: String,
lastName: String,
avatar: String,
preferences: {
theme: String,
notifications: Boolean
}
},
// Embedded for small arrays
recentActivity: [
{
action: String,
timestamp: Date,
metadata: Object
}
]
};
// Reference Pattern for Large Collections
const orderSchema = {
_id: ObjectId,
userId: ObjectId, // Reference to users
items: [
{
productId: ObjectId, // Reference to products
quantity: Number,
price: Number
}
],
total: Number,
status: String,
createdAt: Date
};
|
Frequently Asked Questions
What is MongoDB development?
MongoDB is a document-oriented NoSQL database. MongoDB development involves designing document schemas, implementing aggregation pipelines, setting up replication and sharding, and optimizing for specific query patterns. MongoDB excels at flexible, hierarchical data.
How much does MongoDB development cost?
MongoDB development typically costs $100-150 per hour. A basic implementation starts around $8,000-15,000, while complex deployments with sharding, aggregation pipelines, and performance optimization range from $30,000-80,000+. MongoDB Atlas simplifies operations.
MongoDB vs PostgreSQL: which should I choose?
Choose MongoDB for: flexible/evolving schemas, document-centric data, rapid prototyping, or hierarchical data. Choose PostgreSQL for: relational data, complex joins, ACID requirements, or when you need SQL. Many projects benefit from using both.
How do you design MongoDB schemas?
I follow principles: embed when data is accessed together, reference when data is shared or large, denormalize for read performance, and design for query patterns not data relationships. Good MongoDB schema design is different from relational design.
Can you help optimize slow MongoDB queries?
Yes. I use explain() to analyze queries, create appropriate indexes (including compound and partial), optimize aggregation pipelines, implement proper read preferences, and tune connection pooling. MongoDB can be fast with proper optimization.