Skip to content

Instantly share code, notes, and snippets.

@suhailroushan13
Created December 11, 2025 11:03
Show Gist options
  • Select an option

  • Save suhailroushan13/669b3186e83657e192e143c6ec445d12 to your computer and use it in GitHub Desktop.

Select an option

Save suhailroushan13/669b3186e83657e192e143c6ec445d12 to your computer and use it in GitHub Desktop.
Aggregation in Mongo DB

πŸ“˜ MongoDB Basic Aggregation – Full Guide (Markdown)

βœ… BASE SETUP (Express + Mongoose)

User Model

const UserSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: String,
  isActive: Boolean,
  city: String
});

const User = mongoose.model("User", UserSchema);

πŸš€ API Route Structure

app.get("/api/users/basic", async (req, res) => {
  try {
    const result = await User.aggregate([
      // aggregation stages here
    ]);

    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

🟩 1️⃣ $match β€” Filter Documents

Syntax

{ 
  $match: { field: value } 
}

Common Use Cases

Purpose Example
Equal match { age: 25 }
Greater than { age: { $gt: 20 } }
AND condition { age: { $gt: 18 }, isActive: true }
OR condition { $or: [{ city: "Hyd" }, { age: { $lt: 18 } }] }

Example

{ $match: { isActive: true } }

Output

[
  { "name": "Suhail", "isActive": true },
  { "name": "Ali", "isActive": true }
]

🟦 2️⃣ $project β€” Select / Hide Fields

Syntax

{
  $project: {
    field1: 1,
    field2: 0,
    newField: "$oldField"
  }
}

⚠️ Rules

  • You cannot mix 1 and 0 in the same projection except _id: 0.

Example

{ 
  $project: { 
    name: 1,
    age: 1,
    _id: 0
  } 
}

Output

[
  { "name": "Suhail", "age": 23 },
  { "name": "Ali", "age": 27 }
]

🟨 3️⃣ $addFields β€” Add New or Modify Fields

Syntax

{
  $addFields: {
    newField: expression
  }
}

Common Expressions

Expression Meaning
{ $toUpper: "$name" } Convert string to uppercase
{ $concat: ["Hello ", "$name"] } Concatenate
{ $sum: ["$field1", "$field2"] } Add values
{ $multiply: ["$price", 2] } Multiply

Example

{
  $addFields: {
    nameUpper: { $toUpper: "$name" },
    isAdult: { $gt: ["$age", 17] }
  }
}

Output

[
  { "name": "Suhail", "age": 23, "nameUpper": "SUHAIL", "isAdult": true }
]

πŸŸ₯ 4️⃣ $sort β€” Sort Documents

Syntax

{
  $sort: { field: 1 or -1 }
}

Values

Value Meaning
1 Ascending
-1 Descending

Example

{ $sort: { age: -1 } }

Output

[
  { "name": "Ali", "age": 30 },
  { "name": "Suhail", "age": 23 }
]

🟫 5️⃣ $skip β€” Skip N Documents

Syntax

{ $skip: number }

Example

{ $skip: 5 }

🟧 6️⃣ $limit β€” Limit Number of Documents

Syntax

{ $limit: number }

Example

{ $limit: 10 }

🟩 7️⃣ $count β€” Count Documents

Syntax

{ $count: "totalUsers" }

Example

{ $match: { isActive: true } },
{ $count: "activeUsers" }

Output

[
  { "activeUsers": 42 }
]

πŸš€ FULL EXAMPLE β€” All Basic Stages Combined

app.get("/api/users/basic", async (req, res) => {
  try {
    const result = await User.aggregate([

      // 1️⃣ Filter users
      { $match: { isActive: true } },

      // 2️⃣ Add computed fields
      { 
        $addFields: { 
          nameUpper: { $toUpper: "$name" }
        }
      },

      // 3️⃣ Select fields
      { 
        $project: { 
          name: 1,
          age: 1,
          nameUpper: 1,
          email: 1,
          _id: 0
        }
      },

      // 4️⃣ Sort by age (descending)
      { $sort: { age: -1 } },

      // 5️⃣ Skip 0 docs
      { $skip: 0 },

      // 6️⃣ Limit results to 10
      { $limit: 10 }

      // 7️⃣ Count docs (use separate route)
      // { $count: "total" }
    ]);

    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

πŸŽ‰ End of File

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment