[{$match: { status: 'completed' }}, {$unwind: { path: '$products' }}, {$group: { _id: { state: '$user.state', yearMonth: { $substr: [ '$date_created', 0, 7 ] }, productcat: { $arrayElemAt: [ '$products.category', 1 ] } }, qtySold: { $sum: '$products.quantity' }, totalRevenue: { $sum: '$products.total' }, diffProducts: { $addToSet: '$products.name' } }}, {$group: { _id: { state: '$_id.state', yearMonth: '$_id.yearMonth' }, totalRevenue: { $sum: '$totalRevenue' }, byCategory: { $push: { category: '$_id.productcat', qtySold: '$qtySold', revenue: '$totalRevenue', diffProducts: { $size: '$diffProducts' } } } }}, {$project: { _id: 0, state: '$_id.state', yearMonth: '$_id.yearMonth', numCategories: { $size: '$byCategory' }, salesByCategory: '$byCategory' }}, {$sort: { state: 1, yearMonth: 1 }}]