The following column will introduce you to the Laravel Tutorial column about Laravel complex queries using MongoDB, I hope it will be helpful to friends in need!
Introduction: If you want to perform complex queries when using Laravel, it is not possible to query through functions in the model, so this article mainly records how to use aggregate to perform complex queries.
Mongodb library used by Laravel
composer require jenssegers/mongodb
Group query
The user table contains
city_id: city ID
sex: gender, 1 male, 2 female
age: age
You need to query the average gender and male and female values by grouping by city ID, then in The implementation in laravel is as follows, other frameworks are also similar
$cityId = 1;//城市ID $count = UserModel::query()->raw(function ($collection) use ($cityId) { $aggregate = []; $aggregate[]['$match'] = [ 'city_id' => intval($city_id),//过滤城市 'sex' => ['$in' => [1,2]],//过滤性别 ]; $aggregate[]['$group'] = [ '_id' => '$sex',//更具性别进行分组 'avg_age' => [ '$avg' => '$age',//查询年龄平均值 ] ]; //这里还可以继续添加各种条件 return $collection->aggregate($aggregate)->toArray(); });
The above is the detailed content of About complex queries using MongoDB with Laravel. For more information, please follow other related articles on the PHP Chinese website!