🗄️ Node.js – MongoDB: CRUD Operations
Estimated reading: 3 minutes 41 views

🔍 Node.js – MongoDB Find – Query Documents Efficiently with Node.js


🧲 Introduction – Why Use find() in MongoDB with Node.js?

In MongoDB, find() is the primary method used to retrieve documents from a collection. Whether you’re building dashboards, reports, or search features, learning how to filter, sort, and project data is essential for building powerful Node.js applications.

🎯 In this guide, you’ll learn:

  • How to use find() and findOne() in Node.js
  • Apply filters, projections, and sorting
  • Use limit() and skip() for pagination
  • Handle results using async/await or cursors

⚙️ Setup – MongoDB Connection File (db.js)

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

const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
const dbName = 'appDB';

async function getDB() {
  await client.connect();
  console.log('✅ Connected to MongoDB');
  return client.db(dbName);
}

module.exports = getDB;

🔍 Find One Document – findOne()

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

async function findUser() {
  const db = await getDB();
  const user = await db.collection('users').findOne({ name: 'Alice' });
  console.log('👤 Found user:', user);
}

findUser();

🧪 Output:

{
  _id: "64f8...", name: "Alice", email: "alice@example.com", age: 28
}

✅ Returns the first matching document.


📋 Find Multiple Documents – find().toArray()

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

async function findUsers() {
  const db = await getDB();
  const users = await db.collection('users').find({ age: { $gte: 25 } }).toArray();
  console.log('🧾 Users aged 25+:', users);
}

findUsers();

✅ Converts the result cursor into an array.


🎛️ Apply Projections – Return Specific Fields

const users = await db.collection('users').find(
  { age: { $gte: 25 } },
  { projection: { name: 1, email: 1, _id: 0 } }
).toArray();

📌 Only returns name and email fields, hides _id.


🧭 Sort Results

const users = await db.collection('users')
  .find({})
  .sort({ age: -1 }) // descending
  .toArray();

📌 Use 1 for ascending, -1 for descending.


🔁 Limit and Skip for Pagination

const users = await db.collection('users')
  .find({})
  .skip(5)
  .limit(5)
  .toArray();

✅ Skips the first 5 users and returns the next 5.


🧱 Best Practices for Using find() in Node.js

✅ Practice💡 Why It’s Important
Use projectionsAvoids transferring unnecessary data
Index query fieldsImproves performance on large collections
Use limit() for large queriesPrevents memory overload
Chain sort() and skip()Enables smooth pagination
Validate query inputsPrevents injection or malformed queries

📌 Summary – Recap & Next Steps

The find() and findOne() methods are the foundation of querying in MongoDB. Mastering them allows you to build efficient APIs and filter data in any format your app requires.

🔍 Key Takeaways:

  • Use find() to fetch many, findOne() for a single doc
  • Apply filters ({ age: { $gt: 30 } }) to narrow results
  • Use projections to return only necessary fields
  • Combine sort, skip, limit for advanced queries

⚙️ Real-world relevance:
Used in search engines, dashboard filters, user lists, and reporting systems.


❓FAQs – Using find() in MongoDB with Node.js


What’s the difference between findOne() and find()?
findOne() returns a single object. find() returns a cursor or array of results.


How do I return only selected fields?
✅ Use projection:

{ projection: { name: 1, email: 1, _id: 0 } }

Can I use regex in MongoDB queries?
✅ Yes. Example:

{ name: { $regex: '^A', $options: 'i' } }

How do I paginate results in MongoDB?
✅ Use skip() and limit() chained to your query.


Is it safe to use user input in queries?
✅ Yes, but always sanitize or validate input to prevent query injection.


Share Now :

Leave a Reply

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

Share

🔍 Node.js – MongoDB Find

Or Copy Link

CONTENTS
Scroll to Top