🍃 MongoDB Intermediate

What is the difference between $project and $addFields in MongoDB?

Answer

Both stages reshape documents in an aggregation pipeline, but with different effects on existing fields: $project: reshapes each document — you explicitly include or exclude fields. Any field not mentioned is excluded by default (except _id). Must explicitly set fields you want to keep. { $project: { name: 1, email: 1, fullName: { $concat: ["$firstName", " ", "$lastName"] }, _id: 0 } } — the output document has only: name, email, and the computed fullName. All other fields are dropped. Can both include and add computed fields in one stage. $addFields (alias: $set): adds new fields or overwrites existing fields — ALL existing fields are preserved. { $addFields: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, ageCategory: { $cond: { if: { $gte: ["$age", 18] }, then: "adult", else: "minor" } } } } — the output has ALL original fields PLUS the two new computed fields. When to use each: use $addFields when you want to add computed fields while keeping everything else — cleaner and less verbose than $project when many fields must be preserved; use $project when you want to select a specific subset of fields (reduce document size, implement projections, shape for output). $unset: removes specified fields while keeping all others (opposite of $addFields): { $unset: ["password", "internalId"] }. Performance tip: use $project early to reduce document size flowing through the pipeline.