首页 > 解决方案 > 循环请求数据库与查找

问题描述

我有一个问题,最近很头疼。所以我需要你的帮助。

我有 2 个集合:客户(A)他们的历史付款(B)。现在我需要从A获取所有数据并通过 customer_id 将其映射到B,然后将其显示为报告。A的示例数据为 100,000,B为 500,000。

所以我应该使用查找来映射它并将数据返回到我的代码:

$customer_payments = $mongo_db->aggregate_pipeline('Customers',
    array(
        '$lookup' => array(
            'from' => 'payment_history',
            'localField' => 'customer_id',
            'foreignField' => 'id',
            'as' => 'payment_info',
        ),
    )
);

或者我读取所有A数据并循环它然后一一读取到数据库以获取B数据并映射它?

$customers = $mongo_db->get('Customers');
foreach ($customers as $key => $cus) {
    $payment_info = $mongo_db->where('customer_id', $cus['id'])->get('payment_history');
    $cus['payment_info'] = $payment_info;
}

我使用 PHP 和 MongoDB。我的领导告诉我不要使用查找,而是一一阅读-_-。

毕竟哪一个对我和服务器性能更好?

标签: phpmongodbarchitecture

解决方案


绝对 $lookup

在您的情况下,MongoDB 以非常短的时间和高效的方式通过索引字段执行左外连接两个集合。此外,您可以继续使用payment_info.

手动迭代记录效率极低(100.000 次查询payment_history将花费 PHP / MongoDB 小时......)。


推荐阅读