class Subject(Document):
'''
新闻主题信息
'''
author_ref = ReferenceField(Account,dbref=False) #关联用户
when = DateTimeField(default=datetime.datetime.now, required=True)
title = StringField(max_length=50) ` # 文章标题
`
class Comment(Document):
'''
评论
'''
subject_ref = ReferenceField(Subject,dbref=False) #关联主题
display_name = StringField(max_length=50)
author_ref = ReferenceField(Account,dbref=False)
content = StringField() # 内容
问题:第一个是主贴子表,第二个是评论表,现在要查询出主贴的列表,并且统计出主贴的评论数 有什么好的办法 ?
Just talking about my needs. The number of comments should have an additional field attribute on the main post. Why do you have to count every time? If a post is very popular and has millions of comments, do you still have to count?
Chat with the big guys. There are several ways. This is a very interesting question.
Keep current schema
MongoDB's document model determines that it has no join, so it has to be queried twice. Take a look at the syntax of the Object-Document-Mapper you are using.
Embed comments in the post and count them on the client side.
During Query, the entire document is brought to the client and counted. This part of the data transfer is wasted. But when a single post is displayed, all the information is available. If you don’t have many comments, this schema is the recommended approach. But we can improve further.
Embed comments in posts and count them with aggregation framework.
Use db.posts.aggregate(...), unwind, group. This method is a bit overkilling...
Embed comments in the post and add a counting cache.
You can also keep it as it is as suggested above, but if they are in a doc, an update will count the comments
$push
到comments里,同时$inc
, which maintains consistency very well. When querying, just write out the second projection parameter without comments. For example, you want to find the nearest 10.I searched a lot of information, and finally added a separate statistical attribute