mongodb - 在 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
我有一种预感,我链接聚合中传递的参数的方式。感谢您的投入,谢谢。
解决方案
推荐阅读
- python-3.x - 使用 Google Directory API 创建 gmail 组的权限不足
- java - android.view.InflateException: Binary XML file line #11: Error inflating class EditText in android
- tensorflow - How can I modify ModelCheckPoint in keras to monitor both val_acc and val_loss and save accordingly the best model?
- recursion - (M68k) 为什么我的值没有传递到 D0?
- javascript - 点击计算数字
- kubernetes - 运行“top”时,linkerd cli 返回“无效参数”
- amazon-web-services - AWS Lambda 控制台 - 升级 boto3 版本
- profiling - 如何在 Pytroch 中逐层分析?
- ldap - ldapsearch 没有条目错误 32(openldap)
- google-cloud-platform - 如何增加 COMMITTED_CPUS 配额?