Full Stack Camp
رفتن به کانال در Telegram
Fullstack Camp | Learn. Build. Launch. Join us for a hands-on journey through HTML, CSS, JavaScript, React, Node.js, Express & MongoDB — all in one place. Use this bot to search for lessons. @FullstackCamp_assistant_bot DM: @Tarikey6
نمایش بیشترکشور مشخص نشده استدسته بندی مشخص نشده است
236
مشترکین
اطلاعاتی وجود ندارد24 ساعت
+37 روز
+530 روز
آرشیو پست ها
🚀 Week 8 Day 7 — Relationships, Advanced Querying & Optimization in MongoDB
Hello campers! 💙
Today’s lesson is where your backend becomes smarter, faster, and production-ready.
We’re covering relationships, querying, performance, and aggregation — everything that turns a simple app into a real system.
PART 1 — Relationships & Population
➨Big Idea
In real applications, data is connected:
➝Users create posts
➝Orders have products
➝Comments belong to posts
MongoDB is NoSQL — it doesn’t enforce relationships like SQL does. But we can still link data using references and use populate() to fetch connected data.
➡ Example Models
User model
const userSchema = new mongoose.Schema({
name: String,
email: String });
Post model
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: "User" } });
➨ Analogy
Think of your database like a library:
Users = library members
Posts = books
Each book has a borrower ID → reference to a user
Without .populate() → you see only the user ID, not the user details.
With .populate() → you automatically fetch the user info too.
🔹 Using .populate()
const posts = await Post.find().populate("author");
console.log(posts);
Now each post includes author details, not just the ID.
➡Deep Population
Sometimes, data is nested:
const commentSchema = new mongoose.Schema({
text: String,
post: { type: mongoose.Schema.Types.ObjectId, ref: "Post" },
commenter: { type: mongoose.Schema.Types.ObjectId, ref: "User" } });
Fetch comments with post and user:
const comments = await Comment.find() .populate({ path: "post", populate: { path: "author" } }) .populate("commenter");
➡Analogy
You’re fetching a book, the author of the book, and the person who reviewed it. Deep population = going 2–3 layers deep.PART 2 — Querying & Pagination 1️⃣ Filtering & Query Params Example:
// GET /api/posts?category=tech&author=123
const posts = await Post.find({
category: req.query.category,
author: req.query.author });
➨Filters = search options at an online store.
You want only Electronics, price < $500, sorted by rating.
2️⃣ Pagination (limit + skip)
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const posts = await Post.find() .skip((page - 1) * limit) .limit(limit);
You don’t load 1000 items at once — that’s slow.➡ Text Search
await Post.createIndexes({
title: "text",
content: "text" });
const results = await Post.find({ $text: { $search: "MongoDB" } });
PART 3 — Performance & Optimization
1️⃣ Indexing
Indexing = table of contents for your database.
userSchema.index({ email: 1 });
➝Makes searches faster
➝Reduces full collection scans
2️⃣ Query Optimization Basics
➨Only fetch fields you need → .select("name email")
➨Use lean queries → .lean() → returns plain JS objects, faster than Mongoose documents
❗️Avoid deep nested populates if not needed
🔹 Lean Queries
const users = await User.find().lean();
➝Faster for read-only operations
➝Less memory overhead
➝ Instead of bringing a full encyclopedia, you just photocopy the needed page.
PART 4 — Aggregation Framework
Aggregation = MongoDB’s “Excel for databases”
➝$match → filter documents
➝$group → group & summarize
➝$project → select/transform fields
Example — Average post views by author
const result = await Post.aggregate([
{ $match: { published: true } },
{ $group:
{ _id: "$author", avgViews: { $avg: "$views" } }
},
{ $project: { authorId: "$_id", avgViews: 1, _id: 0 }
} ]);
Think of aggregation as preparing a report:
➨$match → filter your raw data
➨$group → summarize by category
➨$project → format report columns
Deep Aggregation Idea
You can combine $lookup to simulate joins:
const posts = await Post.aggregate([
{ $match: { published: true } },
{ $lookup: { from: "users", localField: "author", foreignField: "_id", as: "authorDetails" }} ]);
➝Like merging two spreadsheets: posts + authors → single report.Happy Easter Fam ❤❤
May this easter bring you the changes you are looking for and fill your home with full happiness.
💥 Week 8 Day 6 — Backend Integration Challenges
Challenge 1 — Library Book API
🎯 Goal
Build a well-structured Express + Mongoose API for managing library books.
Requirements
➝ Use folder structure:
models/
routes/
config/
➝ Use .env for DB connection
➝ Create a Book model with:
- title (required)
- author (required)
- isbn (unique, required)
- publishedYear (min 1900, max current year)
- genre (enum: fiction, nonfiction, sci-fi, biography)
- isAvailable (default true)
API Endpoints
➝ POST /api/books → create a book
➝ GET /api/books → all books
➝ GET /api/books/available → use static method to get only available books
➝ GET /api/books/:id/details → use schema method to return "Title by Author (Year) – Available/Not"
Challenge 2 — Event Management API
🎯 Goal
Add logic + validation rules to an event system.
Requirements
➝ Event model:
- name (required)
- date (required, must be future)
- capacity (min 1)
- category (enum: conference, workshop, social)
- ticketPrice (min 0)
- isCanceled (default false)
Tasks
➝ Create API routes (POST, GET)
➝ Add custom validator → date must be after current date
➝ Create static method:
getUpcomingEvents() → returns events with date >= today and not canceled
➝ Add route to use it
➝ Add a route that updates all past events → set isCanceled = true
Challenge 3 — Task Management System (Clean Architecture)
🎯 Goal
Simulate a real backend with better organization + logic separation.
Requirements
➝ Separate:
- model
- routes
- db config
➝ Use .env
➝ Task model:
- title (required)
- description (required)
- priority (enum: low, medium, high)
- completed (default false)
- dueDate (required)
Tasks
➝ Create routes:
- POST create task
- GET all tasks
➝ Add schema method:
markCompleted() → sets completed = true and saves
➝ Add static method:
getOverdueTasks() → tasks with dueDate < today and not completed
➝ Create route to mark a task as completed (use schema method)
➝ Create route to get overdue tasks (use static method)
When you are done,
💥 Share your solutions,
💥 invite a friend,
and as always —
💥 stay well, stay curious, and stay coding ✌️🚀 Week 8 Day 6 — Backend Integration + Mongoose Deep Dive
Good Evening campers 🔥💙
Today , let's continue from prevous and get deep into Backend integration in a structured way.
🌳 PART 1 — MongoDB + Express
Big Idea
➝Express = handles requests (GET, POST…)
➝Mongoose = handles database
Together = full backend API
🏗 Basic Setup
Install:
npm install express mongoose dotenv🧱 Project Structure Instead of one messy file:
project/
│
├── models/
│
└── User.js
│
├── routes/
│
└── userRoutes.js
│
├── config/
│
└── db.js
│
├── .env
├── app.js
Analogy
Think of this like a company:
models/ → blueprint department
routes/ → customer service (API endpoints)
config/ → system setup
app.js → main building
🔌 Database Connection (config/db.js)
const mongoose = require("mongoose"); const connectDB = async () => { try { await mongoose.connect(process.env.MONGO_URI); console.log("DB Connected ✅"); } catch (err) { console.log(err); process.exit(1); } }; module.exports = connectDB;Environment Variables (.env)
MONGO_URI=mongodb://127.0.0.1:27017/myAppDB PORT=5000Why .env? Never hardcode sensitive data.
.env = secret vault 🔒 Your code = public officeUse dotenv in app.js
require("dotenv").config();
🚀 app.js (Main Server)
const express = require("express");
const connectDB = require("./config/db");
const app = express();
connectDB();
app.use(express.json());
app.use("/api/users", require("./routes/userRoutes"));
app.listen(process.env.PORT, () => console.log("Server running ") );
🚪 Routes (routes/userRoutes.js)
const express = require("express"); const router = express.Router(); const User = require("../models/User"); // CREATE router.post("/", async (req, res) => { const user = await User.create(req.body); res.json(user); }); // READ router.get("/", async (req, res) => { const users = await User.find(); res.json(users); }); module.exports = router;What Just Happened? User sends request → Express route → Mongoose → MongoDB → response back Like: Customer → cashier → warehouse → cashier → customer 🧬 PART 2 — Mongoose Deep Dive Now we upgrade our models from basic → powerful. 🏗 models/User.js
const mongoose = require("mongoose"); const userSchema = new mongoose.Schema({ name: String, age: Number }); module.exports = mongoose.model("User", userSchema);Now let’s LEVEL THIS UP 👇 1️⃣ Schema Validation Required Fields
name: { type: String, required: true }
👉 Must be provided
Min / Max
age: { type: Number, min: 18, max: 60 }
👉 Controls allowed range
Enum (Limited Options)
role: { type: String, enum: ["user", "admin", "moderator"] }
👉 Only specific values allowed
2️⃣ Default Values
isActive: { type: Boolean, default: true }
👉 If not provided → automatically set
3️⃣ Custom Validators
email: { type: String, validate: { validator: function (v) { return v.includes("@"); }, message: "Invalid email" } }
4️⃣ Schema Methods
Methods = functions tied to a document
userSchema.methods.sayHello = function () { return Hello, my name is ${this.name}; };
Usage
const user = await User.findOne();
console.log(user.sayHello());
5️⃣ Static Methods
Statics = functions on the model itself
userSchema.statics.findAdults = function () { return this.find({ age: { $gte: 18 } }); };
Usage
const adults = await User.findAdults();
FULL ADVANCED MODEL EXAMPLE
const mongoose = require("mongoose"); const userSchema = new mongoose.Schema( { name: { type: String, required: true }, age: { type: Number, min: 18, max: 60 }, email: { type: String, validate: { validator: v => v.includes("@"), message: "Invalid email" } }, role: { type: String, enum: ["user", "admin"], default: "user" }, isActive: { type: Boolean, default: true } }); // Method userSchema.methods.greet = function () { return Hi, I am ${this.name}; }; // Static userSchema.statics.getActiveUsers = function () { return this.find({ isActive: true }); }; module.exports = mongoose.model("User", userSchema);
Repost from Edemy
Story time…
Someone asked me a question that often comes up: feeling stuck, wondering if it’s even possible to catch up, or if learning all this makes sense.
Sometimes it’s how others talk about their achievements:
“How are they doing all this already?”
“Why does it feel easy for them but not for me?”
“Am I too slow?”
Sometimes it’s how the tech world is described:
“Is this even for me?”
“Where do I even start?”
“What if I never get it?”
And sometimes, it’s hearing someone call a technology or process “hard” or “advanced,” making it feel impossible.
But everyone’s journey is different, just because it’s hard for one person doesn’t mean it will be for someone else.
The truth is, everyone starts somewhere. Confused. Stuck. Googling everything. Breaking things and starting again.
No one has it all figured out at first. They just keep going. Even now, people are still learning. The struggle doesn’t disappear, the level just changes.
The biggest challenge most people face is themselves.
That voice that says:
“You’re behind.”
“You’re not good enough.”
“You won’t reach where they are.”
We compare. We doubt. We slow ourselves down.
Learning to be kind to yourself matters more than you think.
Because growth comes from consistency, not pressure.
Take small steps. Keep moving. That’s literally how everyone you look up to got there.
And at the end
Ask yourself: is it better to sit and wonder what if, or to try the thing you think is impossible?
Try it, you’ll be surprised how things start to make sense when you invest time, energy, and effort.
@edemy251
💥 Week 8 Day 5 — Mongoose Challenges
🧩 Challenge 1 — User Manager (Basic CRUD App)
🎯 Goal
Build a simple user system using Mongoose.
Requirements
➙Connect to MongoDB (local or Atlas)
➙Create a User schema with:
name
email
age
isActive
Operations
➙Create at least 5 users
➙Get all users
➙Find users with age > 20
➙Update one user’s age
➙Delete one user by email
🧩 Challenge 2 — Product Inventory System
🎯 Goal
Simulate a store backend.
Requirements
➙Create:
Product schema
Fields:
name
price
category
inStock
rating
Operations
➙Insert at least 8 products
➙Find all Electronics products
➙Find products with price between 100–500
➙Sort products by rating (descending)
➙Update all low-rated products (rating < 3) → set inStock = false
➙Delete one product by ID
🧩 Challenge 3 — Blog System (Relationships Thinking)
🎯 Goal
Simulate a simple blog backend.
Requirements
➙Create:
User model and Post model
Post fields:
title
content
author (store user ID)
views
published
Operations
➙Create 2 users
➙Create multiple posts linked to users
➙Find all posts by a specific user
➙Find posts with views > 100
➙Update one post → set published = true
➙Delete one post
When you are done,
💥 Share your solutions ,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️🔴 8️⃣ DELETE (Remove Data)
Delete one
await User.deleteOne({ name: "Sara" });Delete many
await User.deleteMany({ isActive: false });Delete by ID
await User.findByIdAndDelete("id_here");⚡ 9️⃣ Async/Await (VERY IMPORTANT) All database operations are asynchronous. Always use:
async function run() { const users = await User.find(); console.log(users); } run();Why? Database takes time → network + disk operations. Without async: Your code runs before data is ready. 🧱 Example Full Flow (Simple App)
const mongoose = require("mongoose"); mongoose.connect("mongodb://127.0.0.1:27017/testDB") .then(() => console.log("Connected")); const userSchema = new mongoose.Schema({ name: String, age: Number }); const User = mongoose.model("User", userSchema); async function run() { await User.create({ name: "Sara", age: 22 }); const users = await User.find(); console.log(users); } run();🧠 What Just Happened? ➨Connected to DB ➨Defined schema ➨Created model ➨Inserted data ➨Retrieved data That’s a real backend workflow.
🚀 Week 8 Day 5 — Connecting MongoDB with Node.js (Mongoose)
Alright campers 💙
Today our backend will finally talk to a real database.
Up until now:
our data lived in memory (temporary 😢)
Or inside MongoDB tools (manual work)
Today:
our Node.js app becomes alive — it can store, read, update, and delete real data automatically.
🌳 BIG IDEA — Backend ↔ Database Connection
Think of your system like this:
➛MongoDB = 🏬 Warehouse (stores data)
➛Node.js = 👨💼 Manager (handles logic)
➛Mongoose = 📞 Phone line between them
Without Mongoose:
Your backend and database are like two people who can’t communicate.
🧱 Why Mongoose?
You can use MongoDB directly… but it’s messy.
Mongoose gives you:
➙Structure (schemas)
➙Validation
➙Cleaner queries
➙Better developer experience
🛠 1️⃣ Install Mongoose
Inside your project:
npm install mongooseDone. Now your Node app can communicate with MongoDB. 🔌 2️⃣ Connect to MongoDB First, import mongoose:
const mongoose = require("mongoose");Connect (Local MongoDB)
mongoose.connect("mongodb://127.0.0.1:27017/myAppDB") .then(() => console.log("DB Connected ✅")) .catch(err => console.log(err));Connect (Atlas Cloud)
mongoose.connect("mongodb+srv://username:password@cluster.mongodb.net/myAppDB")🧠 What’s Happening? ➝mongodb://... = database address ➝myAppDB = database name ➝.connect() = opening connection ⚠️ Important: Connection must happen before using models. 🧬 3️⃣ Schema — Designing the Shape of Data MongoDB is flexible… but Mongoose introduces structure. A Schema defines how your data should look. Example: User Schema
const userSchema = new mongoose.Schema({ name: String, email: String, age: Number, isActive: Boolean });➨ Analogy Schema = blueprint of a building. Before building a house: ➝You define rooms ➝You define structure 🏗 4️⃣ Model — The Working Tool A Model is created from a schema.
const User = mongoose.model("User", userSchema);🧠 Analogy If Schema = blueprint Then Model = construction company using that blueprint. You don’t interact with schema directly. You use the model to: create read update delete data 🟢 5️⃣ CREATE (Insert Data) Create a new user
const user = new User({ name: "Sara", email: "sara@mail.com", age: 22, isActive: true });Save to database
await user.save();Shortcut (recommended)
await User.create({ name: "John", email: "john@mail.com", age: 25, isActive: true });🔵 6️⃣ READ (Find Data) Get all users
const users = await User.find();Find one user
const user = await User.findOne({ name: "Sara" });Find by ID
const user = await User.findById("id_here");With conditions
const users = await User.find({ age: { $gt: 20 } });🟡 7️⃣ UPDATE (Modify Data) Update one
await User.updateOne( { name: "Sara" }, { $set: { age: 23 } } );Update many
await User.updateMany( { isActive: true }, { $set: { isActive: false } } );Find and update (very common)
const updatedUser = await User.findByIdAndUpdate( "id_here", { age: 30 }, { new: true } );new: true → return updated version
Good news Campers 🤗
From now on you don't have to scroll back to get lessons or challenges, I already made you a telegram bot for that.
Check it out here and give me feedbacks so that I can improve it.
@FullstackCamp_assistant_bot
🧭 Understanding Relationships
In database design, we think about how data relates to other data.
Three common patterns exist.
🟡 1️⃣ One-to-One Relationship
One record relates to exactly one other record.
Example:
User → Profile
User document:
{ "_id": "u1", "name": "Sara" }Profile document:
{ "userId": "u1", "bio": "Backend developer", "location": "Addis Ababa" }One user has one profile. 🟠 2️⃣ One-to-Many Relationship One record relates to multiple records. Example: User → Posts User:
{ "_id": "u1", "name": "Sara" }Posts:
{ "title": "Post 1", "authorId": "u1" }
{ "title": "Post 2", "authorId": "u1" }One user can write many posts. 🧠 Analogy Teacher → Students One teacher teaches many students. 🔴 3️⃣ Many-to-Many Relationship Both sides can relate to many records. Example: Students ↔ Courses Student document:
{ "name": "Sara", "courses": ["course1", "course2"] }Course document:
{ "title": "Databases", "students": ["student1", "student2"] }Multiple students join multiple courses. 🧠 Analogy Think of a gym membership system. Members join many classes. Classes contain many members. 🧠 How Engineers Decide (Important Thinking) When designing schema, engineers ask: 1️⃣ Do we always access this data together? → Embed 2️⃣ Is this data shared across many documents? → Reference 3️⃣ Can the data grow very large? → Reference 4️⃣ Is the relationship simple and small? → Embed There is no single perfect rule — it's about balancing performance and clarity. 🏗 Example Real Application Let's imagine a job platform like the one you built earlier. Users collection:
{ "_id": "user1", "username": "Sara" }Jobs collection:
{ "title": "Frontend Developer", "company": "TechCorp", "postedBy": "user1" }Applications collection:
{ "jobId": "job10", "userId": "user5" }This structure keeps data clean and scalable. Next lesson we’ll move one step closer to real backend systems by connecting MongoDB to Node.js so our applications can actually use the database. Until then — stay well, stay curious, and stay coding ✌️
🚀 Week 8 Day 4 — Schema Design & Data Relationships in MongoDB
Alright campers 🔥💙
Hope you're doing well and still showing up with curiosity and patience.
Today we answer a very important design question:
How should we structure our data?
Because storing data is easy.
Storing it the right way is what real engineers think about.
🌳 BIG IDEA — MongoDB Is Flexible, But Design Still Matters
MongoDB is called schema-flexible.
That means documents in the same collection do not need identical structure.
Example:
Document 1:
{ "name": "Sara", "age": 22 }Document 2:
{ "name": "John", "email": "john@mail.com", "hobbies": ["music", "sports"] }MongoDB allows this. But here's the important truth: Just because you can store data randomly doesn't mean you should. Good schema design means: ➞Data is easy to read ➞Queries are efficient ➞Relationships are clear ➞The system scales well A good engineer plans the shelves before filling them. 🧱 Two Core Design Approaches in MongoDB MongoDB relationships are handled in two main ways: 1️⃣ Embedding documents 2️⃣ Referencing documents 🟢 1️⃣ Embedding Documents Embedding means placing related data inside the same document. Example: A blog post with its comments.
{ "title": "Learning MongoDB", "author": "Sara", "comments": [ { "user": "John", "message": "Great article!" }, { "user": "Liya", "message": "Very helpful!" } ] }Here, comments are embedded directly inside the post document. ✅ When Embedding Is Good: ➞Data is closely related ➞Data is accessed together ➞The amount of nested data is small Examples: Blog post + comments User profile + address Order + purchased items ⚠️ When Embedding Is Not Ideal: ➡The embedded data grows very large ➡Data must be accessed separately ➡Many documents reference the same data Example problem: If thousands of comments exist, embedding them all inside the post could make the document too large. 🔵 2️⃣ Referencing Documents Referencing means storing related data in separate documents and linking them using IDs. Example: Blog posts referencing users. Users collection:
{ "_id": "user123", "name": "Sara", "email": "sara@mail.com" }Posts collection:
{ "title": "Learning MongoDB", "authorId": "user123" }Here the post stores only the author's ID, not the full user data. ✅ When Referencing Is Good: ➡Data is shared across many documents ➡Data is large ➡Data changes frequently Examples: Users and posts Products and orders Students and courses
💥 Week 8 Day 3 — Query Operators Challenges
🧩 Challenge 1 — Advanced Product Filtering
Create or use: storeDB → products
Requirements
➡Insert enough products (if needed), then write queries to:
➙Find products with price between 300 and 1000
➙Find products that are Electronics OR rating > 4.5
➙Find products that have a discount field
➙Find products whose name contains "pro" (case-insensitive regex)
➙Find products that contain BOTH tags "gaming" and "portable"
➙Find products where specs.ram ≥ 16
🧩 Challenge 2 — Student Smart Search
Use: schoolDB → students
Requirements
Write queries to:
➙Find students with GPA between 3.0 and 3.8
➙Find students who are NOT graduated and age > 22
➙Get distinct departments
➙Find students whose name starts with "A" (regex)
➙Find students where a scholarship field exists
➙Find students in Computer Science OR Software Engineering
🧩 Challenge 3 — Blog Post Deep Matching
Use: blogDB → posts
Requirements
Write queries to:
➙Find posts with views > 200 AND published = true
➙Find posts where category is in a list of at least two categories
➙Find posts whose title contains "mongodb" (case-insensitive)
➙Find posts that have exactly 3 tags (use $size)
➙Find posts missing the featured field
➙Combine filters to get top high-view published tech posts
When you are done,
💥 Share your solutions ,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
🟠 5️⃣ Array Operators — Working with Lists
Remember:
tags: ["gaming", "portable"]
Arrays are very common in MongoDB.
Match Array Value
db.products.find({ tags: "gaming" })MongoDB automatically checks inside arrays. ➡All Values — $all
db.products.find({ tags: { $all: ["gaming", "portable"] } })-Must contain BOTH tags. ➡Array Size — $size
db.products.find({ tags: { $size: 2 } })➡Element Match — $elemMatch (important) For complex array objects. 🔵 6️⃣ Nested Field Queries — Dot Notation Power MongoDB handles nested objects beautifully.
specs: { ram: 16, storage: 512 }To query nested fields:
db.products.find({ "specs.ram": { $gte: 16 } })This dot notation is VERY important. Think of it like: Opening boxes inside boxes. 🔴 7️⃣ Regex Queries — Smart Text Search Regex = pattern matching. Used in: ➙search bars ➙autocomplete ➙keyword filtering
db.products.find({ name: { $regex: "lap" } })Matches: ➞Laptop ➞Lapdesk ➞Lap…
{ $regex: "laptop", $options: "i" }The "i" flag = ignore case. ⚠️ Important: Regex is powerful but expensive. Use carefully in large datasets. 🧠 8️⃣ Query Composition Patterns Real power comes from combining operators.
db.products.find({ category: "Electronics", price: { $gte: 500, $lte: 1500 }, rating: { $gt: 4 }, inStock: true })This is how real production queries look. Think of queries like building a filter pipeline. Each condition narrows the results. More filters → more precision. 🎯 After Today You Should Be Able To ✅ Use comparison operators confidently ✅ Combine conditions with logical operators ✅ Check field existence ✅ Query arrays correctly ✅ Query nested fields with dot notation ✅ Use regex for search ✅ Compose complex real-world queries
🚀 Week 8 Day 3 — Query Operators & Data Matching
Morning campers 🔥💙
So far, you’ve been asking MongoDB simple questions like:
“Give me products in Electronics.”
Nice… but real apps ask MUCH smarter questions.
Today you learn how to ask MongoDB:
➛very specific
➛very intelligent
➛very powerful questions.
🌳 BIG IDEA — Queries Are Questions
Every MongoDB query is simply:
“Find documents that match these conditions.”
The magic comes from operators — special tools that help MongoDB filter precisely.
Think of operators like search filters on an online store:
➛price range
➛category
➛rating
➛keyword search
We’ll use this collection throughout:
shopDB → products
{ name: "Gaming Laptop", price: 1200, category: "Electronics", inStock: true, rating: 4.5, tags: ["gaming", "portable"], specs: { ram: 16, storage: 512 } }🔵 1️⃣ Comparison Operators — Value Matching These compare numbers or values. ➥Greater Than — $gt
db.products.find({ price: { $gt: 500 } })➥Greater Than or Equal — $gte { price: { $gte: 500 } } ➥Less Than — $lt { price: { $lt: 1000 } ➥Less Than or Equal — $lte ➥Not Equal — $ne { category: { $ne: "Furniture" } } ➥In List — $in
db.products.find({ category: { $in: ["Electronics", "Accessories"] } })Like: Show items that belong to ANY of these shelves. Not In — $nin -Opposite of $in. 🟣 2️⃣ Logical Operators — Combining Conditions - AND , OR , NOT filters. ➡AND — $and
db.products.find({ $and: [ { price: { $gt: 500 } }, { inStock: true } ] })🧠 Pro tip: MongoDB often assumes AND automatically:
db.products.find({ price: { $gt: 500 }, inStock: true })➡OR — $or
db.products.find({ $or: [ { category: "Electronics" }, { rating: { $gt: 4.5 } } ] })➡NOT — $not ➡NOR — $nor .... 🟢 3️⃣ Element Operators — Field Existence & Type Sometimes you don’t care about the value… You care whether the field exists. ➡Field Exists — $exists
db.products.find({ discount: { $exists: true } })➡Type Check — $type
db.products.find({ price: { $type: "number" } })Used in: ➙data validation ➙migrations ➙debugging messy data 🟡 4️⃣ Evaluation Operators — Special Conditions ➙Regex — $regex (Preview) Used for pattern matching.
db.products.find({ name: { $regex: "laptop", $options: "i" } })Meaning: ➙Find names containing “laptop” (case insensitive). This is like search bars in real apps. ➡Mod — $mod
db.products.find({ price: { $mod: [2, 0] } })
Repost from Edemy
To all the women reading this 😍
Life isn’t always easy, and some days feel heavier than others. Yet, somehow, you keep moving. You keep dreaming. You keep building, even when the path isn’t clear.
You carry so much responsibilities, hopes, and challenges, and still find a way to show up for yourself and others. That is strength. That is courage. That is resilience.
It’s okay to take a pause. It’s okay to rest. Your worth isn’t measured by how much you do or how perfect your day looks. Every step, even the small ones, matters.
To the women facing doubts, breaking barriers, and carving their own path, You are seen. You are strong. You are enough. 💜
Happy Women’s Day 💜
Keep shining, keep rising, and keep believing in the beautiful future you’re creating.
@edemy251
Repost from DoughNut 🍩
One thing I've learned about AI lately is that it will definetly replace software engineers, you might say which ones well software engineers who cant code, think, be creative, problem solve, think building a dashboard takes a week, think technical debt is an imaginary term. It honestly feels like having a really cool junior engineer u can tell it to do the boring stuff u dont wanna do while u focus on tough parts. But it doesnt mean u let it go all in without u knowing what to do. If you think a 20 bucks cursor subscription can build ur product end to end well you're a dumbass. But if u believe a 20 bucks subscription can help u move much faster while you are the senior architect welcome to the new era of software engineering.
💥 Week 8 Day 2 — Core Database Operations Challenges (Medium)
Alright campers 🔥💙
Time to combine your CRUD powers. Use mongosh or Compass.
🧩 Challenge 1 — Store Inventory
Create:
storeDB → products
➞Add at least 10 products using insertMany()
➞Fields: name, price, category, inStock, rating
➞Query Electronics only
price > 300
rating < 3
➞Show only name + price (projection)
➞Sort by price (descending)
➞Skip 5 + limit 5
➞Increase price of Electronics
➞Set inStock = false for rating < 2
➞Delete one product by name
➞Delete all out-of-stock products
🧩 Challenge 2 — Student Analyzer
Create:
schoolDB → students
➡Insert At least 12 students
➡Fields: name, age, department, gpa, graduated
➡Query
gpa > 3.5
not graduated
distinct departments
➡sort by gpa (desc)
➡show only name + gpa
➡Increase GPA for Computer Science students
➡Set graduated = true for gpa > 3.7
➡Remove students with gpa < 2.0
🧩 Challenge 3 — Blog Bulk Operations
Create:
blogDB → posts
➡Insert At least 8 posts
➡Fields: title, author, views, category, published
➡BulkWrite (single command)
➛Insert 2 posts
➛Update views of one
➛Publish one draft
➛Delete one post
➛Query
views > 100
➛sort by views (desc)
➛top 3 posts
When you are done,
💥 Share your solutions ,
💥invite a friend,
and as always —
💥stay well, stay curious, and stay coding ✌️
