Full Stack Camp
Kanalga Telegramāda oātish
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
Ko'proq ko'rsatishMamlakat belgilanmaganToif belgilanmagan
235
Obunachilar
Ma'lumot yo'q24 soatlar
-17 kun
+330 kun
Postlar arxiv
š 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 āļø
