All academies
All projects

Chat Application

Conversations, messages, unread counts, and the bucket pattern.

Schema design

conversations

Last message embedded for the inbox screen (extended reference).

conversations document
{
  _id: ObjectId(),
  participants: [ObjectId(), ObjectId()],
  lastMessage: { text: "See you at 5", senderId: ObjectId(), at: ISODate() },
  unread: { "userA": 0, "userB": 3 }
}

messages

One doc per message; conversationId + time index drives history pagination.

messages document
{
  _id: ObjectId(),
  conversationId: ObjectId(),
  senderId: ObjectId(),
  text: "See you at 5",
  at: ISODate(),
  readBy: [ObjectId()]
}

Key queries

Inbox (conversations, most recent first)

mongosh
db.conversations.find({ participants: me })
  .sort({ "lastMessage.at": -1 }).limit(20)

Message history (infinite scroll)

mongosh
db.messages.find({ conversationId: convId,
  _id: { $lt: lastSeenId } })       // range-based pagination
  .sort({ _id: -1 }).limit(30)

Indexes

db.messages.createIndex({ conversationId: 1, _id: -1 })

History is always per-conversation in reverse time order; _id encodes time.

db.conversations.createIndex({ participants: 1, "lastMessage.at": -1 })

Multikey index answers 'my conversations, newest activity first'.

Aggregations

Messages per day (activity chart)

mongosh
db.messages.aggregate([
  { $match: { conversationId: convId } },
  { $group: { _id: { $substrCP: ["$at", 0, 10] },
              count: { $sum: 1 } } },
  { $sort: { _id: 1 } }
])

Performance tips

  • 1.Use _id-based (range) pagination for history — skip() degrades with depth.
  • 2.Update conversations.lastMessage on every send so the inbox never queries messages.
  • 3.Consider bucketing very old messages into archive documents (bucket pattern).
Want to experiment with these patterns? Open the playground and build the collections yourself, or practice related skills in the challenges.