python - 如何获取包含另一个集合中的键的文档计数

标签 python mongodb flask

我正在建立个人博客

我有两个收藏;帖子和评论

帖子看起来像这样

{
    '_id': ObjectId('5d7bf67d30bb02db73fd491d'),
    'title': 'Comments',
    'post_author': ObjectId('5d7008ce6d6a577820420467'),
    'content': "There is a comment",
    'date_posted': datetime.datetime(2019, 9, 13, 20, 5, 17, 367000)
}

评论看起来像这样

}    '_id': ObjectId('5d7c9717c9fc4f7b8e19e906'), 
     'user': ObjectId('5d7008ce6d6a577820420467'), 
     'post_id': ObjectId('5d7b5aee0de3faa4cc8a1dc0'), 
     'title': 'is this going to get super nested?',
     'content': 'this is getting weird',
     'date_posted': datetime.datetime(2019, 9, 14, 7, 30, 31, 587000)
}

我正在尝试获取每个帖子的评论数量

我一直在尝试循环遍历所有帖子,并使用 count 来获取每个帖子的评论数,如下所示;

def comment_count():
    posts = mongo.db.posts.find().sort("_id", -1)
    for post in posts:
        post_id = post['_id']
        count = mongo.db.comment.count({'post_id': post_id})
        return count

我的模板看起来像这样

{% for post in posts %}
        <div class="posts z-depth-2">
            <div class="post-card">
                <span class="post-title"><a href="{{ url_for('post', post_id=post._id) }}">{{ post.title }}</a></span>
                {{ comment_count }}
                {% if post.date_posted %}
                <span class="post-date">{{ post.date_posted.strftime("%d %b %Y") }}</span>
                {% endif %}
                <hr>
            </div>
            <p>{{ post.content }}</p>
        </div>
{% endfor %}

当我从模板中调用 comment_count 来显示每个帖子的评论数时,无论实际评论数如何,它都会为所有帖子返回 6。我希望它实际上能给出正确的计数。

最佳答案

您实际上可以使用aggregation framework来做到这一点。您需要运行的操作由 post 集合上的一个管道组成,该管道执行 $lookup添加到 comments 集合并创建一个额外字段,该字段返回数组 $lookup 中的项目计数管道步骤产生。

考虑运行以下聚合操作:

def posts_with_comment_count():
    pipeline = [
        { "$lookup": {
            "from": "comment",
            "localField": "_id",
            "foreignField": "post_id",
            "as": "comment_count"
        } },
        { "$addFields": {
            "comment_count": { "$size": "$comment_count" }
        } },
        { "$sort": { "_id": -1 } }
    ]
    posts = list(mongo.db.posts.aggregate(pipeline))

    return posts

关于python - 如何获取包含另一个集合中的键的文档计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941559/

相关文章:

python - 遍历一个大列表

javascript - 用随机时间更新集合中的每条记录?

mongodb - 即使 GeoJSON 有效,也无法提取地理键

python - HTTP 检索错误 Twilio

python unittest.main() 不运行测试用例

python - `join` 或 `format` 字符串哪个更好?

python - 如何从文件中提取非常大的 HDF5 数据集并写入另一个文件?

python - 确定 dask 计算某事物的次数

javascript - Mongo 和 Node js 的查询返回不重复、不同

python - 在 Flask session 中保留上传数据以进行分析