Home > PHP Framework > Laravel > About complex queries using MongoDB with Laravel

About complex queries using MongoDB with Laravel

藏色散人
Release: 2021-01-20 09:31:11
forward
2972 people have browsed it

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!

About complex queries using MongoDB with Laravel

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
Copy after login

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();
});
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template