🍃 MongoDB Intermediate

What is the difference between $unwind and $lookup in MongoDB?

Why Interviewers Ask This

Mid-level MongoDB roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

$unwind: deconstructs an array field from input documents to output one document for each element of the array. Given a document with an array of 3 elements, $unwind produces 3 documents, each with a single value instead of the array. { $unwind: "$tags" }. Options: includeArrayIndex: "tagIndex" (add field with element's index); preserveNullAndEmpty: true (keep documents where the field is null, missing, or an empty array — otherwise they're removed). Use cases: group by array elements (count documents per tag), filter array elements (match inside arrays), join arrays with $lookup. $lookup: joins another collection to the current documents — adds data from another collection as an embedded array. { $lookup: { from: "products", localField: "productId", foreignField: "_id", as: "productDetails" } }. Together: $lookup + $unwind is a common pattern. After $lookup adds an array of matched documents, $unwind flattens it (like a JOIN with multiple matches becoming multiple rows): [ { $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "orders" } }, { $unwind: "$orders" }, { $group: { _id: "$_id", name: { $first: "$name" }, totalSpent: { $sum: "$orders.total" } } } ]. Key difference: $unwind works on arrays within a document; $lookup brings in arrays from another collection. They solve different problems but frequently work together for multi-collection aggregations.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex MongoDB answers easy to follow.