Node.js MongoDB: Find Documents

Welcome to The Coding College! In this tutorial, we’ll explore how to find and retrieve data from a MongoDB collection using Node.js. Retrieving data is one of the most essential operations in any database-driven application, and MongoDB offers powerful methods to query and filter documents.


Prerequisites

Before you begin, ensure the following:

  1. MongoDB Installed: Download MongoDB.
  2. Node.js Installed: Download Node.js.
  3. MongoDB Driver Installed: Install the MongoDB driver with: npm install mongodb

Step 1: Setup MongoDB Connection

Create a file findData.js and establish a connection to MongoDB:

const { MongoClient } = require('mongodb');

// MongoDB connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database and Collection
const dbName = 'myNewDatabase';
const collectionName = 'users';

async function findDocuments() {
  try {
    // Connect to MongoDB
    await client.connect();
    console.log('Connected to MongoDB server.');

    // Select the database and collection
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Fetch all documents
    const documents = await collection.find().toArray();
    console.log('Documents found:', documents);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    // Close the connection
    await client.close();
    console.log('Connection closed.');
  }
}

findDocuments();

Step 2: Query Documents with Filters

To retrieve specific documents, pass a filter object to the find() method. For example, find users with age greater than 25:

async function findFilteredDocuments() {
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Filter for users older than 25
    const filter = { age: { $gt: 25 } };
    const documents = await collection.find(filter).toArray();
    console.log('Filtered Documents:', documents);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
  }
}

findFilteredDocuments();

Step 3: Retrieve a Single Document

Use the findOne() method to fetch a single document:

async function findOneDocument() {
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Find a document by email
    const query = { email: '[email protected]' };
    const document = await collection.findOne(query);
    console.log('Document found:', document);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
  }
}

findOneDocument();

Step 4: Sort Results

To sort documents, use the sort() method. For example, sort by age in descending order:

async function findAndSortDocuments() {
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Sort by age in descending order
    const documents = await collection.find().sort({ age: -1 }).toArray();
    console.log('Sorted Documents:', documents);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
  }
}

findAndSortDocuments();

Step 5: Limit Results

Use the limit() method to restrict the number of documents returned:

async function findAndLimitDocuments() {
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Limit results to 2 documents
    const documents = await collection.find().limit(2).toArray();
    console.log('Limited Documents:', documents);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
  }
}

findAndLimitDocuments();

Step 6: Combine Filters, Sort, and Limit

You can combine filters, sorting, and limits to customize your queries. For example:

async function complexQuery() {
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // Filter, sort, and limit
    const filter = { age: { $gte: 20 } };
    const documents = await collection
      .find(filter)
      .sort({ name: 1 })
      .limit(5)
      .toArray();

    console.log('Complex Query Results:', documents);
  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await client.close();
  }
}

complexQuery();

Best Practices

  1. Index Fields: Create indexes for fields you frequently query to improve performance.
  2. Pagination: Use skip() and limit() for paginated results.
  3. Error Handling: Handle errors gracefully and log them for debugging.
  4. Projection: Use projection to limit the fields returned, reducing data transfer: const documents = await collection.find({}, { projection: { name: 1, age: 1 } }).toArray();

Example Output

For the above queries, you might see output like this:

Connected to MongoDB server.
Documents found: [
  { _id: ObjectId("64d12345abcd6789ef123456"), name: 'John Doe', email: '[email protected]', age: 30 },
  { _id: ObjectId("64d12345abcd6789ef123457"), name: 'Alice', email: '[email protected]', age: 25 },
]
Connection closed.

Conclusion

Using Node.js to query MongoDB gives you robust options for retrieving data, from basic fetching to complex filtering and sorting. For more programming tutorials, check out The Coding College and continue advancing your coding skills.

Leave a Comment