1. MongoDB $match Aggregation

Definition

The $match stage in MongoDB's aggregation pipeline filters documents based on specified conditions. It acts like a query operator to filter documents before passing them to the next stage. This is typically used as an early stage in the pipeline to reduce the number of documents that need processing.

Algorithm 1: Basic $match Usage :-
  • Step 1: Select your collection
  • Step 2: Define match criteria
  • Step 3: Apply comparison operators if needed
  • Step 4: Structure the match query
  • Step 5: Execute the pipeline
  • Example 1: Simple Match Filtering
    // Filter students with high math scores
    db.students.aggregate([
    {
    $match: {
    mathScore: { $gte: 90 },
    grade: "A"
    }
    }
    ])
    Algorithm 2: Advanced $match Operations :-
  • Step 1: Identify complex filter conditions
  • Step 2: Combine multiple conditions
  • Step 3: Use logical operators
  • Step 4: Apply regex or array operators if needed
  • Step 5: Test the filter results
  • Example 2: Complex Match Conditions
    // Complex matching with multiple conditions
    db.orders.aggregate([
    {
    $match: {
    $and: [
    { status: "active" },
    { orderDate: { $gte: ISODate("2023-01-01") } },
    { totalAmount: { $gt: 1000 } },
    { "customer.type": "premium" },
    { tags: { $in: ["electronics", "gadgets"] } }
    ]
    }
    }
    ])