Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forum Model For MongoDB

So I am creating a model for a forum. Think thread and a bunch of comments where. Thread has many comments. In RDBMS world, I would design this as such

Thread --has many--> Comment
id                   id
user_id              thread_id
                     user_id 

Now, I guess, with this, the data/schema would follow one of the many normal forms (I forgot which). And I think this is the most sensical way to do it. However, when it comes to doing this in NoSQL world (MongoDB), what would be the best way to design this relationship? I could almost do it in the RDBMS way, but I would lose the advantage of using embedded object. For some reason, I am more inclined to do it like

Thread
_id
user_id
comments => [{_id, user_id, body, created_at}]

What would be the most sensical way to do this I guess that's what I am asking. And why?

like image 385
denniss Avatar asked Jan 28 '12 06:01

denniss


People also ask

Is MongoDB good for forum?

MongoDB is a general purpose database and fits with most use cases. You can definitely build a discussion forum using MongoDB.

What is model in MongoDB?

Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database. Compiling your first model.

What is realm MongoDB?

Realm is an embedded, object-oriented database that lets you build real-time, offline-first applications. Its SDKs also provide access to Atlas App Services, a secure backend that can sync data between devices, authenticate and manage users, and run serverless JavaScript functions.

What is a MongoDB cluster?

A sharded cluster in MongoDB is a collection of datasets distributed across many shards (servers) in order to achieve horizontal scalability and better performance in read and write operations.


1 Answers

First off, I hope you have read the docs on Schema Design, which explains with an example similar to yours.

So, you can embed or link according to your choice. I would embed if the number of comments are expected to be manageable (relatively smaller) and link if there would be too many comments.

Embedding has the advantage that only one single DB call is required to show a single post/thread and most usually can send just the mongodb response to the browser as is (if client side does the UI rendering). *Note: And adding a comment will require an UPDATE using $push. And do remember that the comment._id has to be created by you, MongoDB won't auto-create it for you. Any updates of comment data in embedded scenario will require an UPDATE with the $ positional operator.*

like image 181
rsmoorthy Avatar answered Oct 04 '22 21:10

rsmoorthy