How to store comments in NoSQL (MongoDB)?

1 way

Comments are embedded in the Post document:

{
  "_id": ObjectId(12345),
  "title": "Cat ate elephant!",
  "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean convallis pretium vulputate.",
  "comments": [
    {"name": "Cat", "body": "MEOW!"},
    {"name": "Elephant", "body": "I was eaten by cat, lol!"},
    {"name": "Human", "body": "I am hungry!"}
  ]
}

2 way

The relationship between mail and comments (in separate documents). The post has many comments:

// POST //
{
  "_id": ObjectId(12345),
  "title": "Cat ate elephant!"
  "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean convallis pretium vulputate."
}


// Comments //

{
  "_id": ObjectId(...),
  "post_id": ObjectId(12345),
  "name": "Cat",
  "body": "MEOW!"
}

{
  "_id": ObjectId(...),
  "post_id": ObjectId(12345),
  "name": "Elephant",
  "body": "I was eaten by cat, lol!"
}

{
  "_id": ObjectId(...),
  "post_id": ObjectId(12345),
  "name": "Human",
  "body": "I am hungry!"
}

Which way is better?

+3
source share
3 answers

Method 1

  • No need to join => quick access to data
  • NoSQL way to do it
  • Each comment is associated only with this post, so why not save them together (you keep the header and body together;)

If you have large documents,> 15.5 megabytes, and you receive a reward for comments, you may have to store them somewhere else. This is because the maximum document size is 16 megabytes.

2 - RDMBS , Mongo , .

+2

, Post NoSQL. , , , 1 .

+2

The first method is preferred if the document is not difficult to write. If within a minute you add 5,000 comments to the post, use the second method.

+2
source

All Articles