
Mongodb Query in NodeJs
Querying MongoDB in Node.js is super flexible! You can filter, sort, and manipulate results easily — either using the native MongoDB driver or Mongoose.
✅ 1. Using Native MongoDB Driver
📦 Step 1: Install
npm install mongodb
🔍 Step 2: Query Examples
const { MongoClient } = require('mongodb');const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);async function runQueries() { try { await client.connect(); const db = client.db('myDatabase'); const users = db.collection('users'); // 👉 Find all users const all = await users.find().toArray(); console.log('All Users:', all); // 👉 Find one user const one = await users.findOne({ name: 'Alice' }); console.log('One User:', one); // 👉 Filter: users older than 25 const filtered = await users.find({ age: { $gt: 25 } }).toArray(); console.log('Age > 25:', filtered); // 👉 Sort: by age descending const sorted = await users.find().sort({ age: -1 }).toArray(); console.log('Sorted by age desc:', sorted); // 👉 Pagination: skip 5, limit 5 const paginated = await users.find().skip(5).limit(5).toArray(); console.log('Page results:', paginated); } finally { await client.close(); }}runQueries();
🪄 2. Using Mongoose
📦 Step 1: Install
npm install mongoose
🔍 Step 2: Query Examples
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(() => console.log('Connected!'));// Define schema and modelconst userSchema = new mongoose.Schema({ name: String, age: Number });const User = mongoose.model('User', userSchema);async function queryUsers() { // 👉 Find all const all = await User.find(); console.log('All:', all); // 👉 Find one const one = await User.findOne({ name: 'Bob' }); console.log('One:', one); // 👉 Filter: age > 20 const filtered = await User.find({ age: { $gt: 20 } }); // 👉 Sort and limit const sorted = await User.find().sort({ age: -1 }).limit(3); console.log('Filtered:', filtered); console.log('Top 3 by age:', sorted); mongoose.disconnect();}queryUsers();
🧠 Common MongoDB Query Operators
Operator | Meaning | Example |
---|---|---|
$gt , $lt | Greater / less than | { age: { $gt: 25 } } |
$eq , $ne | Equal / not equal | { name: { $ne: 'Alice' } } |
$in , $nin | In / not in array | { name: { $in: ['A', 'B'] } } |
$or | OR conditions | { $or: [{ age: 20 }, { age: 30 }] } |
$regex | Pattern match | { name: /al/i } (contains "al") |
Let me know if you want to:
Build advanced queries
Create API endpoints for querying
Add pagination or search