
Mongodb Find in NodeJs
Finding documents in MongoDB using Node.js is one of the most common operations you'll perform. Let's look at how to do it using both:
✅ Native MongoDB Driver
🪄 Mongoose (the beginner-friendly ODM)
✅ 1. Using Native MongoDB Driver
📦 Step 1: Install the driver
npm install mongodb
🔍 Step 2: Find Documents
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/myDatabase') .then(async () => { console.log('Connected to MongoDB'); // Define schema and model const userSchema = new mongoose.Schema({ name: String, age: Number }); const User = mongoose.model('User', userSchema); // Find all const allUsers = await User.find(); console.log('All users:', allUsers); // Find with condition const usersOver25 = await User.find({ age: { $gt: 25 } }); console.log('Users over 25:', usersOver25); // Find one const oneUser = await User.findOne({ name: 'Bob' }); console.log('Found:', oneUser); await mongoose.disconnect(); }) .catch(err => console.error(err));
🔍 Common Query Options
MongoDB Query Syntax | What It Does |
---|---|
{ age: { $gt: 18 } } | Find where age > 18 |
{ name: /ali/i } | Case-insensitive name search (regex) |
{ $or: [a, b] } | Match if a OR b is true |
find().limit(5) | Limit results to 5 |
find().sort({ age: -1 }) | Sort by age descending |