Node.js Tutorial
Estimated reading: 3 minutes 18 views

๐Ÿง  Node.js โ€“ MongoDB: Advanced Queries โ€“ Querying, Sorting, Limiting & Joining Collections

๐Ÿงฒ Introduction โ€“ Go Beyond Basic CRUD with Powerful MongoDB Queries

While basic CRUD operations help you manage records, real-world applications require advanced querying techniques to filter, sort, paginate, join, and clean up data effectively. With Node.js and MongoDB, these actions are performed with minimal, readable code using the native driver.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to use find() with advanced filters
  • How to sort and limit query results
  • How to simulate joins using $lookup
  • How to safely drop entire collections

๐Ÿ“˜ Topics Covered

๐Ÿ”น Topic๐Ÿ“– Description
๐Ÿงพ Node.js โ€“ MongoDB QueryUse query operators for conditional filtering
๐Ÿ”ข Node.js โ€“ MongoDB SortSort query results by any field
โ›” Node.js โ€“ MongoDB LimitLimit the number of documents returned
๐Ÿ”— Node.js โ€“ MongoDB JoinUse aggregation and $lookup to simulate SQL-style joins
๐Ÿ—‘๏ธ Node.js โ€“ MongoDB Drop CollectionPermanently delete an entire collection

๐Ÿงพ Node.js โ€“ MongoDB Query

๐Ÿ”น Use Query Filters

const client = require('./db');

async function filterEmployees() {
  const db = client.db('myCompany');
  const results = await db.collection('employees').find({ salary: { $gt: 50000 } }).toArray();
  console.log(results);
}

filterEmployees();

๐Ÿงช Output:

Returns all employees with salary greater than 50000

โœ… Use operators like $gt, $lt, $ne, $in, $or, and $regex for complex filtering.


๐Ÿ”ข Node.js โ€“ MongoDB Sort

async function sortBySalary() {
  const db = client.db('myCompany');
  const results = await db.collection('employees').find().sort({ salary: -1 }).toArray();
  console.log(results);
}

sortBySalary();

๐Ÿงช Output:

Employees sorted by salary in descending order

โœ… Use 1 for ascending and -1 for descending sort.


โ›” Node.js โ€“ MongoDB Limit

async function limitEmployees() {
  const db = client.db('myCompany');
  const results = await db.collection('employees').find().limit(2).toArray();
  console.log(results);
}

limitEmployees();

๐Ÿงช Output:

Returns only the first 2 employee documents

โœ… Combine sort() and limit() for effective pagination.


๐Ÿ”— Node.js โ€“ MongoDB Join (Using $lookup)

๐Ÿ”น Simulate SQL JOIN Between Two Collections

Assume you have:

departments

{ "_id": 1, "name": "HR" }

employees

{ "name": "Alice", "department_id": 1 }
async function joinEmployeeWithDepartment() {
  const db = client.db('myCompany');
  const results = await db.collection('employees').aggregate([
    {
      $lookup: {
        from: "departments",
        localField: "department_id",
        foreignField: "_id",
        as: "department_info"
      }
    }
  ]).toArray();

  console.log(results);
}

joinEmployeeWithDepartment();

๐Ÿงช Output:

[
  {
    name: "Alice",
    department_id: 1,
    department_info: [ { _id: 1, name: "HR" } ]
  }
]

โœ… MongoDB does not support traditional joins but $lookup achieves a similar effect.


๐Ÿ—‘๏ธ Node.js โ€“ MongoDB Drop Collection

async function dropCollection() {
  const db = client.db('myCompany');
  await db.collection('employees').drop();
  console.log("Collection dropped!");
}

dropCollection();

๐Ÿงช Output:

Collection dropped!

โœ… Use with caution. This will permanently remove all documents in the collection.


๐Ÿ“Œ Summary โ€“ Recap & Next Steps

MongoDB provides flexible, powerful tools for working with your data beyond CRUD. Node.js makes it easy to apply advanced filters, sort results, control data volume, and even simulate relational joinsโ€”all with JSON-like syntax.

๐Ÿ” Key Takeaways:

  • Use query operators like $gt, $in, and $regex for filtering
  • Sort using .sort({ field: 1 or -1 })
  • Limit records with .limit(n)
  • Simulate joins using $lookup in aggregation
  • Drop collections carefully with .drop()

โš™๏ธ Real-World Uses:

  • Dashboard search filters with sort and limit
  • Paginated product listings
  • Department-employee relationship queries
  • Scheduled cleanup scripts (e.g., drop stale logs)

โ“ Frequently Asked Questions

โ“ Can MongoDB perform joins like SQL?
โœ… Yes, using the $lookup operator in aggregation pipelines to link documents across collections.


โ“ How do I sort multiple fields?
โœ… Use:

.sort({ department: 1, salary: -1 })

This sorts first by department ascending, then by salary descending.


โ“ Is limit() required for pagination?
โœ… Yes. Combine limit() with skip(n) for accurate pagination:

.find().skip(10).limit(5)

โ“ Does dropping a collection affect the database?
โœ… It removes the collection entirely, but the database remains. Use .dropDatabase() to remove the full database.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿง  Node.js โ€“ MongoDB: Advanced Queries

Or Copy Link

CONTENTS
Scroll to Top