Nested comments in MongoDB

I am very new to MongoDB and trying to create a nested comment system in it. On the net you will find various document structures to achieve this, but I am looking for some suggestions that would allow me to easily do the following with comments

  • Mark comments as spam / approved and get comments on these attributes
  • Get user comments
  • Get comment counter for object / user

In addition, of course, displaying comments, as is usually done. If you have any suggestions on how to handle these things using MongoDB, or - tell me to look for an alternative, that would be very helpful!

+3
source share
2 answers

Due to the fact that you need to receive comments on certain attributes, the user, etc., you cannot embed (embedding is always faster for document databases) a comment in each object that users can comment on. Therefore, you need to create a separate collection for comments. I suggest the following structure:

comment { _id : ObjectId, status: int (spam =1, approved =2), userId: ObjectId, commentedObjectId: ObjectId, commentedObjectType: int(for example question =1, answer =2, user =3), commentText } 

With the above structure, you can easily do what you need:

 //Mark comments as spam/approved and retrieve comments by this attributes //mark specific comment as spam db.comments.update( { _id: someCommentId }, { status: 1 }, true); db.comments.find({status : 1});// get all comments marked as spam //Retrieve comments by user db.comments.find({'_userId' : someUserId}); //Retrieve comment count for an object/user db.comments.find({'commentedObjectId' : someId,'commentedObjectType' : 1 }) .count(); 

Also, I believe that for comments, it would be better to create an additional field in each object and inc add / delete it in the comment.

+1
source

Have you considered storing comments in all documents requiring links to them? If you have a document for the user, save all these user comments in it. If you have a separate document for objects, save all comments as well. This seems wrong after you come from the relational world, where you try to get exactly one copy of a given piece of data and then refer to it by identifier, but even with relational databases you have to start duplicating the data if you want the queries to be executed fast.

With this design, each downloadable document will be "complete." It will have all the necessary data, and the indexes in this collection will read quickly. The price will be a little slower, writing and more of a headache when you need to update the comment text, since you need to update more than one document.

+1
source

All Articles