如何通过Laravel REST Api控制器从特定列mongodb集合中检索不同的行数?



我有一个基于react的web应用程序,后端由Laravel编写的REST API支持。我需要在数据库中显示从一个集合中的特定列的计数,之后它将显示在仪表板上。这应该通过mongodb查询和对后端的API调用从后端检索。作为Laravel/MongoDb的新手,当我试图在我的控制器上完成这个实现时,我遇到了一个阻碍-这是我需要实现想法的部分-基本上是如何向数据库发出请求并检索结果。下面的代码显示了目前为止的代码:

我的mongodb查询,它在mongo shell上工作并返回167如计数:

db.users.distinct('policy_scheme').length

php代码:

api.php:

Route::get('totalSchemes', [CollectionController::class, 'numberOfSchemes']);

控制器:

public function numberOfSchemes(Request $request)
{
$schemeCount = DB::collection('users')::distinct()->get(['policy_scheme'])->count();

if(!empty($schemeCount)){
return response()->json([
'message'=>'data', 
'data'=> $schemeCount], 201);
}
else{
return response()->json([
'message'=>'No data', 
'data'=>[] ], 201);
}

}

我不确定,但试试这个

$schemeCount = DB::collection('users')::unique('id')->get(['policy_scheme'])->count();

最新更新