rgtk
rgtk

Reputation: 3500

How to store comments in NoSQL (MongoDB)?

1 way

Comments are embedded in 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

Relationship between Post and Comments (in separate documents). 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?

Upvotes: 10

Views: 7226

Answers (3)

Mattias
Mattias

Reputation: 9471

Method 1

  • No need to joins => fast access to data
  • The NoSQL way of doing it
  • Every comment is just related to just that post, so why not store them together(you store the title and the body together ;)

If you have large documents, >15.5 Megabyte, and you gets a loot of comments then you probably will need to store them somewhere else. This because the maximum document size is 16 Megabyte.

Method 2 is the RDMBS way of doing it, Mongo does not have joins inbuilt so you will need to do them in your application.

Upvotes: 4

000
000

Reputation: 27227

The first way is preferred, as long as the document is not write-heavy. If you're going to have 5000 comments added to a post within a minute, then use the second method.

Upvotes: 4

Leon
Leon

Reputation: 859

Because no comment belongs to more than one post, it makes more sense to embed them in the Post document in NoSQL. So when you retrieve your Post you immediately have your comments as well, in 1 query.

Upvotes: 3

Related Questions