Lesson 30 +20 XP

MongoDB Project

MongoDB Project

Put it all together! You'll model a small blog database, query it, and analyze it - using everything you've learned.

Step 1: Set up the database

use blog

Step 2: Insert posts

db.posts.insertMany([
  { title: "First", category: "News", likes: 5, tags: ["news"] },
  { title: "Second", category: "Tech", likes: 12, tags: ["tech", "news"] },
  { title: "Third", category: "News", likes: 2, tags: ["news"] }
])

Step 3: Query the data

// All news posts
db.posts.find({ category: "News" })

// Posts with more than 3 likes, sorted
db.posts.find({ likes: { $gt: 3 } }).sort({ likes: -1 })

Step 4: Update and delete

// Give every post one more like
db.posts.updateMany({}, { $inc: { likes: 1 } })

// Remove the post named "Third"
db.posts.deleteOne({ title: "Third" })

Step 5: Analyze with an aggregation

db.posts.aggregate([
  { $group: { _id: "$category", totalLikes: { $sum: "$likes" } } },
  { $sort: { totalLikes: -1 } }
])

This totals the likes per category and puts the most popular category first.

What you practiced

  • Creating a database and inserting documents.
  • Finding with filters, sorting, and $gt.
  • Updating with $inc and deleting with deleteOne.
  • Aggregating with $group, $sum, and $sort.

TL;DR

  • CRUD: insertMany, find, updateMany, deleteOne.
  • Analysis: aggregation with $group + $sum.
  • Keep data structured so queries are easy to write.