You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel jenssegers/mongodb中单次查询获取多个字段平均值

解决方案

简洁写法(贴合你原始预期的查询风格)

$productStats = ProductDetails::where('id', $id)
    ->where('active', true)
    ->groupByRaw(null)
    ->selectRaw('AVG(price) as avg_price, AVG(margin) as avg_margin, AVG(weight) as avg_weight')
    ->first();

// 直接取值即可
$avgPrice = $productStats->avg_price;
$avgMargin = $productStats->avg_margin;
$avgWeight = $productStats->avg_weight;

这个写法和你最开始预期的查询逻辑完全一致,只需要把原来的select替换为selectRaw写入聚合函数,加上groupByRaw(null)指定全局聚合不需要按字段分组即可,底层会自动转换为MongoDB的聚合查询执行,全程只发起一次请求。


原生聚合管道写法(适合复杂统计场景扩展)

$productStats = ProductDetails::raw(function ($collection) use ($id) {
    return $collection->aggregate([
        // 匹配过滤条件,和where逻辑完全一致,优先过滤减少后续计算量
        [
            '$match' => [
                'id' => $id,
                'active' => true
            ]
        ],
        // 分组计算平均值,_id设为null代表全局聚合不需要按字段拆分
        [
            '$group' => [
                '_id' => null,
                'avg_price' => ['$avg' => '$price'],
                'avg_margin' => ['$avg' => '$margin'],
                'avg_weight' => ['$avg' => '$weight']
            ]
        ]
    ]);
})->first();

之前写法的问题说明

find方法仅用于文档查询,无法执行聚合计算,$avg是MongoDB的聚合操作符,仅可在聚合管道的$group/$project等阶段使用,不能写入find的查询条件中。

内容的提问来源于stack exchange,提问作者Thbwun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:45:04