Schemas

following things while designing the schema in MongoDB

  1. Always design schema according to user requirements.
  2. Do join on write operations not on read operations.
  3. Objects which you want to use together, should be combined into one document. Otherwise they should be separated (make sure that there should not be need of joins).
  4. Optimize your schema for more frequent use cases.
  5. Do complex aggregation in the schema.
  6. You should duplicate the data but in a limit, because disc space is cheaper than compute time.

For example:

let us take an example of a client who needs a database design for his website. His website has the following requirements:

Every post is distinct (contains unique title, description and url).

Every post can have one or more tags.

Every post has the name of its publisher and total number of likes.

Each post can have zero or more comments and the comments must contain user name, message, data-time and likes.

For the above requirement, a minimum of three tables are required in RDBMS.

But in MongoDB, schema design will have one collection post and has the following structure:

{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user: ‘COMMENT_BY’,
message: TEXT,
datecreated: DATE_TIME,
like: LIKES
},
{
user: ‘COMMENT_BY’,
message: TEST,
dateCreated: DATE_TIME,
like: LIKES
}}}