MongoDB: Finding Documents

Subject: nodejs

MongoDB: Finding Documents

Finding documents in MongoDB is the process of retrieving data from collections based on specific criteria. This is akin to the SELECT statement in SQL, allowing you to fetch records that match your requirements.

Why Find Documents?

Finding documents is a core operation for any data-driven application. It enables you to:

  • Display Data: Show records on web pages or reports.
  • Filter Information: Fetch only what you need (e.g., products by price).
  • Search Functionality: Enable field-based searching.
  • Populate Views: Load data into forms or dashboards.

Core Concepts

  • Document: The basic unit of data in MongoDB, stored as key-value pairs.
  • Collection: A group of documents; the target of find operations.
  • Query Document: Specifies matching criteria (e.g., { name: "Laptop" }).
  • Projection Document: Controls which fields are returned (e.g., { name: 1, _id: 0 }).

Methods for Finding Documents

MongoDB provides two key methods:

  • find(query, projection): Returns a cursor for all matching documents. Use .toArray() to read them.
  • findOne(query, projection): Returns the first match or null.

Common Query Operators:

  • $eq, $ne: Equal / Not equal
  • $gt, $gte: Greater than / Greater than or equal
  • $lt, $lte: Less than / Less than or equal
  • $in: Match any value in array
  • $and, $or: Logical combinations
  • $regex: Pattern matching

Node.js Examples: Finding Documents

Prerequisites

  • MongoDB (local or Atlas)
  • Node.js installed
  • MongoDB driver: npm install mongodb

1. Finding All Documents (find({}))

Explanation: An empty query ({}) returns all documents in the products collection.

Expected Output:


2. Finding with Criteria (find({ field: value }))

Explanation: Finds documents where category is Electronics.

Expected Output:


3. Using Query Operators and Projection

Expected Output:


4. Finding One Document (findOne)

Explanation: Returns the first document with name equal to Laptop Pro, or null.

Expected Output:


Key Takeaways

  • find() retrieves multiple documents using a cursor (use .toArray() for array format).
  • findOne() retrieves a single matching document.
  • Query documents define filter criteria.
  • Projections control returned fields.
  • MongoDB offers rich query operators for powerful filtering.
Next : Querying Documents