All academies
All projects

Social Media Feed

Posts, follows, likes, and a fan-out news feed.

Schema design

posts

Like count is denormalized; recent likers embedded for display.

posts document
{
  _id: ObjectId(),
  authorId: ObjectId(),
  authorName: "priya",      // extended reference
  text: "Shipped my first MongoDB app!",
  likeCount: 42,
  recentLikers: ["aarav", "sara"],
  createdAt: ISODate()
}

follows

One document per follow edge — scales to millions of edges.

follows document
{ _id: ObjectId(), follower: ObjectId(), followee: ObjectId(), at: ISODate() }

likes

One doc per like; unique compound index prevents double-likes.

likes document
{ _id: ObjectId(), postId: ObjectId(), userId: ObjectId(), at: ISODate() }

Key queries

Feed (pull model): posts by people I follow

mongosh
const following = db.follows.find({ follower: me })
  .map(f => f.followee)
db.posts.find({ authorId: { $in: following } })
  .sort({ createdAt: -1 }).limit(20)

Like a post (idempotent)

mongosh
db.likes.insertOne({ postId, userId, at: new Date() }) // unique index rejects dupes
db.posts.updateOne({ _id: postId }, { $inc: { likeCount: 1 } })

Indexes

db.follows.createIndex({ follower: 1, followee: 1 }, { unique: true })

One edge per pair; supports 'who do I follow' queries.

db.posts.createIndex({ authorId: 1, createdAt: -1 })

Feed generation reads each followed author's recent posts.

db.likes.createIndex({ postId: 1, userId: 1 }, { unique: true })

Prevents double-liking at the database level.

Aggregations

Trending posts (last 24h, weighted)

mongosh
db.posts.aggregate([
  { $match: { createdAt: { $gte: yesterday } } },
  { $addFields: { score: { $add: ["$likeCount",
      { $multiply: ["$commentCount", 2] }] } } },
  { $sort: { score: -1 } }, { $limit: 20 }
])

Performance tips

  • 1.Pull-model feeds are fine to ~1k follows; beyond that, fan-out-on-write to a feeds collection.
  • 2.Store likeCount on the post — never count the likes collection per render.
  • 3.Cap recentLikers to a few names with $push + $slice.
Want to experiment with these patterns? Open the playground and build the collections yourself, or practice related skills in the challenges.