Aggregation Optimization in MongoDB: Unnecessary Unwinds (Part 2)
A MongoDB expert walks through the first optimization step for a slow aggregation pipeline in a video streaming service use case. The pipeline was originally designed with an RDBMS mindset, using two unnecessary $unwind stages after $lookup joins. The key insight: when $lookup's localField points to a field inside array elements, MongoDB automatically runs the join for each element — making the preceding $unwind redundant. The second $unwind, used to filter out empty arrays, was replaced with a simpler $match stage. Removing both $unwinds also eliminated the need for a subsequent $group stage, reducing the pipeline from 10 to 8 stages. The result was a 60% performance improvement, dropping average query time from 11.8 seconds to 4.7 seconds, though still short of the 1-second SLA target.