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

标签 mongodb python-2.7 flask jinja2 pymongo

考虑下图。我在 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/

相关文章:

javascript - Mongoosejs 在 for 循环中使用 Promise

python - Pandas 根据索引加入两个数据框

android - 在没有互联网的情况下从 WLAN 请求下载时,下载不会在 Android 9 上启动

python - flask-jwt 如何处理 token ?

reactjs - Cognito/Flask/React:如何登录到后端?

node.js - 在放入 Mongoose 之前检查集合是否存在

mongodb - 需要在mgo中使用分页

java - 如何为 mongodb 启用身份验证并与 Spring Boot 连接?

mysql - Python django 外键 (1048, "Column ' USER_ID' cannot be null")

python - 我们如何等待消息文本在 selenium 中弹出