Node.js Tutorial
Estimated reading: 3 minutes 268 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 :
Share

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

Or Copy Link

CONTENTS
Scroll to Top