gpt4 book ai didi

mongodb - 在 Pymongo 中创建集合之间的关系并渲染它 Jinja

转载 作者:行者123 更新时间:2023-12-01 16:56:27 25 4
gpt4 key购买 nike

考虑下图。我在 MongoDB 中有两个集合,我想渲染结果,只需匹配名称就可以得到所需的输出。

我的问题是当我尝试像这样编写代码时无法建立关系:

{% for i in new %}
<h4 class>New Price - {{ i.Product }}</h4>
{% for z in Preowned %}
{% if z['Product'] == i.Product %}
<h4 class>Preowned Price - {{z.Price}}</h4>
{%endif %}
{% endfor %}
{% endfor %}

我真的被困在这里,不知道如何处理这个问题。如果您对我的问题有替代解决方案,请提供帮助。

enter image description here

最佳答案

您可以使用 lookup stage 编写聚合查询对其他集合执行左外连接。请注意此功能是在 Mongo 3.2 中引入的。

假设两个集合都是 collection1collection2,然后从图表中绘制,您的查询将如下所示:

pipeline = [
{
'$lookup': {
'from': 'collection2',
'localField': 'Product',
'foreignField': 'Product',
'as': 'Matches'
}
}
]

db.collection1.aggregate(pipeline)

在 Jinja 中,你可以这样写:

{% for new_item in new_items %}
<h4>New Price - {{ new_item.Product }}</h4>
{% for preowned in new_item.Matches %}
<h4>Preowned Price - {{ preowned.Price }}</h4>
{% endfor %}
{% endfor %}

关于mongodb - 在 Pymongo 中创建集合之间的关系并渲染它 Jinja,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50331691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com