我试图使用php从mongodb获取所有记录。 我有两个系列。问题是,在实践中,我能够为数据库中的每条记录做一个简单的句子吗? :
ie:john [来自名字收藏]住在城市[来自城市收藏]谁 驱动[来自汽车收藏]。
这是上述的正确编码吗?我仍然是一个试图逐步学习的新手
<?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>'} ?>
欢迎您的想法
答案 0 :(得分:0)
将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/>';
}
}
}
?>
这就是当我试图访问多个集合中的数据以形成输出时我是如何做到的
答案 1 :(得分:0)
我希望这可以和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'];
}
这样的事情可以解决问题。
此处我假设您的用户架构中分别包含city
和ride
ID,并且这两个ID字段存储ObjectId
(_id
)的{ {1}}和city
行;这似乎是最合乎逻辑的架构。