简体   繁体   English

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

[英]mongodb gathering all records from different collections

i am trying to grab all records from mongodb using php. 我试图使用php从mongodb获取所有记录。 i have two collections. 我有两个收藏。 question is, in practice will i be able to make a simple sentence such as for each record on the database? 问题是,在实践中,我能否为数据库中的每个记录写一个简单的句子? :

ie: john[from names collection] lives in city[from city collection] who drives[from car collection]. 即:约翰[来自名字收集]居住在城市[来自城市收集],谁开车[来自汽车收集]。

Is this the correct coding for the above? 这是上述正确的编码吗? I am still a newbie trying to learn step by step 我还是新手,想一步一步学习

 <?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>'} ?>

your thoughts are welcome 欢迎您的想法

Nest the for loops inside of each other. 将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/>'; 
}
 }
  }
?> 

Thats how i do it when im trying to access data in multiple collections to form the output 那就是我试图访问多个集合中的数据以形成输出时的处理方法

I expect this to be used with, say, a user_id of sorts. 我希望这可以与user_id之类的一起使用。 Doing a full table scan of this would be a really bad idea. 对此进行全表扫描将是一个非常糟糕的主意。

Here is what you can do providing you have the 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'];
}

Something like that would do the trick. 诸如此类的事情就可以解决问题。

Here I assume that your user schema has a city and ride ID in it respectively and that the two ID fields store an ObjectId ( _id ) of a city and ride row; 在这里,我假设您的用户架构中分别包含cityride ID,并且两个ID字段存储cityride行的ObjectId_id ); this seems to be the most logical schema. 这似乎是最合乎逻辑的模式。

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

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