๐Ÿง  Node.js โ€“ MongoDB: Advanced Queries
Estimated reading: 3 minutes 24 views

๐Ÿงพ Node.js โ€“ MongoDB Query โ€“ Powerful Data Retrieval Techniques with Node.js


๐Ÿงฒ Introduction โ€“ What Are MongoDB Queries in Node.js?

In MongoDB, a query is how you retrieve data that matches certain conditions. Using Node.js, you can write powerful queries to search, filter, and project data from collectionsโ€”essential for building APIs, admin panels, and intelligent search features.

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

  • How to use filter queries with MongoDBโ€™s Node.js driver
  • Combine logical operators like $and, $or, $not
  • Use comparison operators ($gt, $lt, $in, etc.)
  • Best practices for performance and readability

โš™๏ธ Setup โ€“ MongoDB Project and Connection

Install the official driver:

npm install mongodb

๐Ÿ“ db.js โ€“ Reusable connection module:

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;

๐Ÿ” Basic Query โ€“ Find Documents by Field Match

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

async function findUsersByRole() {
  const db = await getDB();
  const users = await db.collection('users').find({ role: 'admin' }).toArray();
  console.log('๐Ÿ‘ค Admins:', users);
}

findUsersByRole();

โœ… Fetches all users where the role equals 'admin'.


๐Ÿ”Ž Comparison Operators

const users = await db.collection('users').find({
  age: { $gte: 25, $lte: 40 }
}).toArray();

๐ŸŽฏ Retrieves users aged between 25 and 40 (inclusive).


๐Ÿ“› Logical Operators โ€“ $and, $or, $not

$or Example:

const users = await db.collection('users').find({
  $or: [{ role: 'admin' }, { age: { $gt: 50 } }]
}).toArray();

โœ… Matches users who are admins or age over 50.

$and Example:

const users = await db.collection('users').find({
  $and: [{ age: { $gt: 20 } }, { status: 'active' }]
}).toArray();

โœ… Matches users who are older than 20 and active.


๐Ÿ“ฅ Use $in and $nin for Array Matching

const users = await db.collection('users').find({
  country: { $in: ['India', 'USA'] }
}).toArray();

โœ… Matches users from either India or USA.


๐Ÿงพ Regex Queries โ€“ Pattern Matching

const users = await db.collection('users').find({
  name: { $regex: '^A', $options: 'i' }
}).toArray();

โœ… Matches names that start with “A”, case-insensitive.


๐Ÿ“‘ Project Fields Using projection

const users = await db.collection('users').find(
  { status: 'active' },
  { projection: { name: 1, email: 1, _id: 0 } }
).toArray();

โœ… Returns only name and email fields.


๐Ÿงฑ Best Practices for MongoDB Query in Node.js

โœ… Practice๐Ÿ’ก Why It Matters
Use indexes on frequently queried fieldsBoosts query performance
Use projectionsReduces bandwidth and improves performance
Combine filters carefullyPrevents overly broad queries
Validate user inputsAvoids injection and malformed queries
Use cursors for large datasetsEfficient memory usage with large queries

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

MongoDB queries in Node.js are flexible and expressive. With operators like $and, $or, $in, and regex, you can filter nearly any data shape to build precise results for your apps.

๐Ÿ” Key Takeaways:

  • Use find() with filters and projections for full control
  • Combine operators for advanced conditions
  • Use regex for flexible string matching
  • Project only needed fields using { projection: { field: 1 } }

โš™๏ธ Real-world relevance:
Used in product filters, search boxes, admin dashboards, analytics, and permission checks.


โ“FAQs โ€“ MongoDB Query in Node.js


โ“ Whatโ€™s the difference between find() and findOne()?
โœ… findOne() returns the first match, find() returns a cursor to all matches.


โ“ How can I use dynamic filters in Node.js?
โœ… Build your query object in JavaScript before passing to find():

const filter = { age: { $gte: minAge } };

โ“ Can I query nested fields?
โœ… Yes, using dot notation:

{ "address.city": "Delhi" }

โ“ How do I limit or skip documents in a query?
โœ… Use .limit() and .skip():

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

โ“ Is it safe to use user-provided filters?
โœ… Yes, but always sanitize inputs and avoid directly inserting untrusted values.


Share Now :

Leave a Reply

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

Share

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

Or Copy Link

CONTENTS
Scroll to Top