Z
Z
Zaharov2011-07-18 21:03:38
MongoDB
Zaharov, 2011-07-18 21:03:38

How to properly organize comments when using Mongo DB?

It is necessary to create a comment system for some materials. I read recommendations that it is better to store all comments in one document, there are no problems here. But besides the comments themselves, nicknames, avatars and other personal belongings of the users who publish them are still needed.
If we store the ObjectID, then we will have to make a bunch of queries to pull out information about the authors. If you save information in the document along with comments, then not only will the document become thicker with duplicate information, but also the user's data will not be updated.
What is the best way to proceed in this situation?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
b0beR, 2011-07-18
@Zaharov

I think it's best to keep comments and user information separate. Accordingly, for each comment, write the author's ObjectID (well, or just id as a number). A bunch of requests in this case is completely unnecessary. After receiving the list of comments, you just need to go through them and add all the id of the authors into an array, then make ONE request, and get all the authors (naturally, only those fields that are needed). Like this:
authors = db.users.find({"_id": {"$in": authors_ids_array}}, {"nickname": 1, "photo": 1});
The actual query on the indexed field will be instant, even with a large number of requested users. After that, I think it will not be a problem to correlate comments with the received users :)
Separately, regarding the storage of the comments themselves. There are 2 options here.
If you need to be able to select all comments of a certain author quite often, then it is best to create a separate collection for comments (that is, store each comment in a separate document), with indexed author_id and topic_id fields. But in this case, the number of documents in the collection can grow to enormous proportions.
If there are no such requests, or they are quite rare, then it is faster and more convenient to store all the comments of a certain material in an array in the document of this very material, and then there will be no need to refer to another collection when receiving the material and its comments. Requesting all comments of a certain author in this case is also possible, although it will be somewhat slower.

V
VBart, 2011-07-18
@VBart

What author information are you going to store in comments? Most likely, all you need is the author's nickname, aka the author's __id. Or can you change your nickname? It is also convenient to link an avatar to a nickname.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question