首页 > 解决方案 > 在 python 中排序和加入 mongodb 集合

问题描述

我需要知道为什么我的聚合查询在测试期间失败。

藏书长这样,

_id: 573a13a6f29313caabd17bd5
title: "TinTin And the Picaros"

评论集合看起来像这样,

_id: 5a9427648b0beebeb69579cc
name :"Andrea Le"
email :"andrea_le@fakegmail.com"
book_id : 573a1390f29313caabcd418c
text: "Rem officiis eaque repellendus amet eos doloribus. Porro dolor volupta..."
date: 2012-03-26 23:20:16.000

一本书可以有多个评论。评论集合中的 book_id 字段和书籍集合中的 _id 字段将两者联系起来。

我需要检索评论并按日期排序。我想出的聚合在函数 get_book 中,

def get_book(id):
 books = db.books.aggregate([
            {
                '$lookup': {
                    'from': 'comments',
                    'let': {
                        'book_id': id
                    },
                    'pipeline': [
                        {
                            '$match': {
                                '$expr': {
                                    '$eq': [
                                        '$book_id', '$$book_id'
                                    ]
                                }
                            }
                        }, {
                            '$sort': {
                                'date': -1
                            }
                        }
                    ],
                    'as': 'comments'
                }}]).next()

        return books

测试功能如下,

def test_fetch_comments_for_book(client):
    book_id = "573a13a6f29313caabd17bd5"
    result = get_book(book_id)
    assert len(result.get('comments', [])) == 2

测试失败并出现错误,

 AssertionError: assert 0 == 2

我有一种预感,我链接聚合中传递的参数的方式。感谢您的投入,谢谢。

标签: mongodbpymongo

解决方案


推荐阅读