繁体   English   中英

mongodb收集来自不同集合的所有记录

[英]mongodb gathering all records from different collections

我试图使用php从mongodb获取所有记录。 我有两个收藏。 问题是,在实践中,我能否为数据库中的每个记录写一个简单的句子?

即:约翰[来自名字收集]居住在城市[来自城市收集],谁开车[来自汽车收集]。

这是上述正确的编码吗? 我还是新手,想一步一步学习

 <?php foreach ($details as $doc) {
echo $doc['name'] . ' lives in'; } 
foreach ($place as $city) {
echo $city['name'] . ' who drives a '; }
foreach ($car as $ride) {
echo $ride['name']; 
echo '<br>'} ?>

欢迎您的想法

将for循环相互嵌套。

<?php 

foreach ($details as $doc) {
 foreach ($place as $city) {
  foreach ($car as $ride) {
   echo $doc['name'] . ' lives in '.$city['name'].' who drives a '.$ride['name'].'<br/>'; 
}
 }
  }
?> 

那就是我试图访问多个集合中的数据以形成输出时的处理方法

我希望这可以与user_id之类的一起使用。 对此进行全表扫描将是一个非常糟糕的主意。

如果您拥有user_id可以执行以下操作:

$users = $mongo->users->find(['_id' => ['$in' => [1,2,3,4,5,6,7,8,9]]]);

// Set some variables which will help us perform the detail queries
$cityIds = [];
$rideIds = [];
$userResults = [];
$cityResults = [];
$rideResults = [];

// Iterate through our users.
foreach($users as $_id => $user){

    // We store the MongoId for use in queries
    $cityIds[] = $user['city_id'];
    $rideIds[] = $user['ride_id'];

    // We then store the user result itself so we don't 
    // Do this query multiple times.
    $userResults[$_id] = $user;
}

// Now, let's get our first details.
$cityResults = iterator_to_array(
    $mongo->cities->find(['_id' => ['$in' => $cityIds]])
);

// And our ride details
$rideResults = iterator_to_array(
    $mongo->rides->find(['_id' => ['$in' => $rideIds]])
);

// Now let's loop and echo
foreach($userResults as $k => $user){
    echo $user['name'] . 
        ' lives in ' . 
        $cityResults[$user['city_id']]['name'] . 
        ' who drives a ' . 
        $rideResults[$user['ride_id']]['name'];
}

诸如此类的事情就可以解决问题。

在这里,我假设您的用户架构中分别包含cityride ID,并且两个ID字段存储cityride行的ObjectId_id ); 这似乎是最合乎逻辑的模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM