Skip to content

Latest commit

 

History

History
248 lines (214 loc) · 5.73 KB

File metadata and controls

248 lines (214 loc) · 5.73 KB

import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem";

👐 $match and $project

MongoDB’s Aggregation Framework allows for powerful data transformations and analysis. The $match, $project, and $sort stages are fundamental building blocks of an aggregation pipeline.


🔹 $match → Filtering data

Just like .find() based on the query mentioned, the $match stage filters documents from the collection.

Syntax

{ $match: { <query> } }

Example: Get all the books that were published after the year 2010

db.books.aggregate([
  {
    $match: { year: { $gt: 2010 } },
  },
]);

:::info Place $match as early as possible in the pipeline to reduce the number of documents processed in later stages. :::


🔹 $project → Selecting fields

  • The $project stage controls which fields are included in the output.
  • It can also be used for adding computed fields to the results.

Syntax

{
  $project: {
    field1: 1,
    field2: 1,
    _id: 0
  }
}
  • 1: Include the field
  • 0: Exclude the field

Example: Get all the books published after the year 2010. The output should only include the title, year, and page count of the book.

db.books.aggregate([
  {
    $match: { year: { $gt: 2010 } },
  },
  {
    $project: {
      title: 1,
      year: 1,
      pages: 1,
      _id: 0,
    },
  },
]);

Equivalent SQL query

SELECT title, year, pages FROM books WHERE year>2010;

Computed fields example: Along with the title and authors, also output the count of authors for every book in the database.

db.books.aggregate([
  {
    $project: {
      title: 1,
      authors: 1,
      authorCount: { $size: "$authors" },
    },
  },
]);

Challenge 🚀

👐 1. Find books with more than 2 available copies.

Answer
```js await books.aggregate([ { $match: {available: {$gt: 2}}} ]).toArray(); ```
```js db.books.aggregate([ { $match: {available: {$gt: 2}}} ]); ```
```csharp var pipeline = booksCollection.Aggregate() .Match(b => b.Available > 2);
    var plentifulBooks = pipeline.ToList();

    if (plentifulBooks != null)
    {
      foreach (var book in plentifulBooks)
      {
        Console.WriteLine($"Title: {book.Title} - Available: {book.Available}");
      }
    }
    else
    {
      Console.WriteLine("Empty Collection");
    }
    ```
  </div>
</TabItem>
<TabItem value="python" label="Python">
  <div>
    ```python
    books_two_copies = books.aggregate([
        {"$match": {"available": {"$gt": 2}}}
    ])

    for book in books_two_copies:
        print(book)
    ```
    </div>
</TabItem> 
 <TabItem value="java" label="Java">
  <div>
    ```java
    books.aggregate(
        List.of(
            Aggregates.match(gt(
                "available", 2)))
        ).forEach(document -> System.out.println(document.toJson()));
    ```
  </div>
</TabItem>

👐 2. Find books with more than 2 available copies. Return only book titles and publication year.

Answer
```js await books.aggregate([ { $match: {available: {$gt: 2}}}, { $project: {title: 1, year: 1, _id: 0}} ]).toArray(); ```
```js db.books.aggregate([ { $match: {available: {$gt: 2}}}, { $project: {title: 1, year: 1, _id: 0}} ]); ```
```csharp var pipeline = booksCollection.Aggregate() .Match(b => b.Available > 2) .Project(b => new { b.Title, b.Year });
    var plentifulBooks = pipeline.ToList();

    if (plentifulBooks != null)
    {
      foreach (var book in plentifulBooks)
      {
        Console.WriteLine($"Title: {book.Title} - Year: {book.Year}");
      }
    }
    else
    {
      Console.WriteLine("Empty Collection");
    }
    ```
  </div>
</TabItem>
<TabItem value="python" label="Python">
  <div>
    ```python
    books_two_copies = books.aggregate([
        { "$match": { "available": { "$gt": 2 } } },
        { "$project": { "title": 1, "year": 1, "_id": 0 } }
    ])

    for book in books_two_copies:
        print(f"Title: {book['title']} - Publication Year: {book['year']}")
    ```
  </div>
</TabItem>
<TabItem value="java" label="Java">
  <div>
    ```java
    books.aggregate(
        List.of(
            Aggregates.match(gt("available", 2)),
            Aggregates.project(
                Projections.fields(
                    Projections.include("title", "year"), 
                    Projections.exclude("_id")
                )
            )
        )
    ).forEach(document -> System.out.println(document.toJson()));
    ```
  </div>
</TabItem>