const popularFilters = await
AnalyticsEvent.aggregate([
// Stage 1: Only filter events
{ $match: {
eventType: 'filter_apply',
createdAt: {
$gte: sixMonthsAgo
}
}},
// Stage 2: Group by month + filter
{ $group: {
_id: {
month: { $dateToString: {
format: '%Y-%m',
date: '$createdAt'
}},
filter: '$metadata.filterName'
},
count: { $sum: 1 }
}},
// Stage 3: Sort by month, then count
{ $sort: {
'_id.month': -1, count: -1
}},
// Stage 4: Reshape output
{ $project: {
_id: 0,
month: '$_id.month',
filter: '$_id.filter',
count: 1
}}
]);
const sizeTrends = await
Image.aggregate([
{ $match: {
createdAt: { $gte: threeMonthsAgo }
}},
{ $group: {
_id: { $dateToString: {
format: '%Y-%m-%d',
date: '$createdAt'
}},
avgSize: { $avg: '$fileSize' },
totalSize: { $sum: '$fileSize' },
count: { $sum: 1 },
maxSize: { $max: '$fileSize' },
}},
{ $sort: { _id: 1 } },
{ $project: {
_id: 0,
date: '$_id',
avgSizeMB: {
$round: [{
$divide: ['$avgSize', 1048576]
}, 2]
},
totalSizeMB: {
$round: [{
$divide: ['$totalSize', 1048576]
}, 2]
},
count: 1,
}}
]);
const usersWithStats = await
User.aggregate([
{ $lookup: {
from: 'images',
localField: '_id',
foreignField: 'owner',
as: 'images'
}},
{ $project: {
name: 1,
email: 1,
imageCount: { $size: '$images' },
totalSize: {
$sum: '$images.fileSize'
},
joinedAt: '$createdAt',
}},
{ $sort: { imageCount: -1 } },
{ $limit: 20 },
]);
async function deleteAccount(userId) {
const session =
await mongoose.startSession();
try {
session.startTransaction();
// Delete all user's images
await Image.deleteMany(
{ owner: userId }, { session });
// Delete all analytics events
await AnalyticsEvent.deleteMany(
{ userId }, { session });
// Delete the user
await User.findByIdAndDelete(
userId, { session });
// All succeeded → commit
await session.commitTransaction();
return { success: true };
} catch (error) {
// Any failure → rollback ALL
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
}
git switch -c feature/PIXELCRAFT-071-aggregation
git add server/
git commit -m "Add aggregation pipeline + transactions (PIXELCRAFT-071)"
git push origin feature/PIXELCRAFT-071-aggregation
# PR → Review → Merge → Close ticket ✅
ACID properties are the foundation of reliable databases.
Transactions guarantee ACID — the properties that prevent your data from becoming corrupted, even during crashes.