Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Mongodb Query in NodeJs

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

bash

npm install mongodb


🔍 Step 2: Query Examples

js

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

bash

npm install mongoose


🔍 Step 2: Query Examples

js

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

OperatorMeaningExample
$gt, $ltGreater / less than{ age: { $gt: 25 } }
$eq, $neEqual / not equal{ name: { $ne: 'Alice' } }
$in, $ninIn / not in array{ name: { $in: ['A', 'B'] } }
$orOR conditions{ $or: [{ age: 20 }, { age: 30 }] }
$regexPattern 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

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql