CPCODELAB
MongoDB

$project, $unwind and $addFields

10 min read

Reshaping Documents in the Pipeline

$project is the pipeline equivalent of a projection — it can include/exclude fields and create computed fields using expressions. $unwind deconstructs an array field into one document per element. $addFields adds new fields without removing existing ones.

js
// Create a fullLabel field and keep only name + course
db.students.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      course: 1,
      fullLabel: { $concat: ["$name", " — ", "$course"] }
    }
  }
]);

// Unwind the tags array
db.students.aggregate([
  { $unwind: "$tags" },
  { $group: { _id: "$tags", total: { $sum: 1 } } },
  { $sort: { total: -1 } }
]);

$unwind on a missing or null field silently drops the document by default. Pass { preserveNullAndEmptyArrays: true } to keep those documents.

Ready to test yourself?
Practice MongoDB— quiz & coding exercises