mongodb 联合查询问题
高洛峰
高洛峰 2017-04-21 11:18:37
0
3
602
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()                          # 内容

问题:第一个是主贴子表,第二个是评论表,现在要查询出主贴的列表,并且统计出主贴的评论数 有什么好的办法 ?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
小葫芦

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.

  1. 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.

  2. 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.

  3. Embed comments in posts and count them with aggregation framework.
    Use db.posts.aggregate(...), unwind, group. This method is a bit overkilling...

  4. 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.

db.posts.find({}, { comments: -1 }).sort({"when": -1}).limit(10)
伊谢尔伦

I searched a lot of information, and finally added a separate statistical attribute

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template