如何在 php 中从 mongodb 集合中获取所有记录


How to fetch all the records from mongodb collection in php

我尝试使用以下代码从mongodb集合中选择所有记录。但只有最后插入的记录才会出现。

<?php 
$m=new MongoClient();
$db=$m->trip;
if($_SERVER['REQUEST_METHOD']=="POST")
{
    $userId=$_POST['userId'];
    $param=explode(",",$userId);
    $collection=$db->chat;
    $record=$collection->find(array("userId"=>$userId));
    if($record)
    {
        foreach($record as $rec)
        {
            $json=array("msg"=>$rec);
        }
    }
    else
    {
        $json=array("msg"=>"No Records");
    }
}
else
{
    $json=array("msg"=>"Request Method is Not Accespted");
}
//output header
header('Content-type:application/json');
echo json_encode($json);

?>

但只有一张唱片会到来请帮助我

您的问题是每次执行foreach时,它都会覆盖$json变量的内容。尝试先声明$json,然后再使用它。

if($record)
{
    $json = array();
    foreach($record as $rec)
    {
        $json[] = array("msg"=>$rec);
        //   /' this means adding the attribution to the end of the array.
    }
}

这样,每次执行foreach时,$json的内容都不会被替换,而是会被追加。