简体   繁体   中英

mongodb gathering all records from different collections

i am trying to grab all records from mongodb using php. 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.

<?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. 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 :

$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; this seems to be the most logical schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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