Exploring MongoDB Aggregation Stages: Code Examples and Applications - Part 3

Photo by Ilya Pavlov on Unsplash

Exploring MongoDB Aggregation Stages: Code Examples and Applications - Part 3

$match:

Filters documents to pass only the documents that match the specified condition.

db.collection.aggregate([
    { $match: {field: value} }
])

$project:

Reshapes the documents in the pipeline, including or excluding fields and changing the data structure

db.collection.aggregate([
    { $project: {field1: 1, field2: 0, field3: { $toUpper: "$field4" } } }
])

$group:

Groups documents together to calculate aggregate values based on the specified grouping fields

db.collection.aggregate([
    { $group: { _id: "$field1", count: { $sum: 1 } } }
])

$sort:

Sorts the documents in the pipeline.

db.collection.aggregate([
    { $sort: {field1: 1} }
])

$limit:

Limits the number of documents passed to the next stage in the pipeline

db.collection.aggregate([
    { $limit: 10 }
])

$skip:

Skips a specified number of documents before passing the remaining documents to the next stage in the pipeline

db.collection.aggregate([
    { $skip: 10 }
])

$unwind:

Deconstructs an array field from the input documents to output a document for each element

db.collection.aggregate([
    { $unwind: "$field1" }
])

$lookup:

Performs a left outer join to an unsharded collection in the same database to filter in documents from the joined collection for processing

db.collection.aggregate([
    {
      $lookup:
        {
          from: "collection2",
          localField: "field1",
          foreignField: "field2",
          as: "joined_field"
        }
   }
])

$out:

Writes the resulting documents of the aggregation pipeline to a specified collection

db.collection.aggregate([
    { $out: "collection2" }
])

These are some of the most commonly used aggregation pipeline stages in MongoDB. You can use these stages in any order to perform complex data processing and analysis tasks

If you missed the previous articles in this series you can find them here.

Exploring MongoDB Aggregation Stages: Code Examples and Applications - Part 1

Exploring MongoDB Aggregation Stages: Code Examples and Applications - Part 2