I am using Laravel with MongoDB and jenssegers package. I have a collection called ProductDetails in which I have three fields for which I need to retrieve the average value: price, margin and weight. I can make three different queries but I would like to get that in one query. I think it would be cleaner. I tried using raw expressions but I cannot make it work. I can't even retrieve the average of a single value. I have seen many people using mongoDB aggregation but I don't see why and how it would be useful here.
Here's what I'd love to achieve:
$productDetails = ProductDetails::select('AVG(price) as avg_price','AVG(margin) as avg_margin','AVG(weight) as avg_weight')
->where('id', '=', $id)
->where('active', '=', true)
->get();
It works when I try to retrieve the values (not the average) but the select does not work with AVG()
which is why I wanted to use raw expressions
This is an unfruitful attempt:
$productDetails = ProductDetails::raw(function($collection)
{
return $collection ->find([
'name' => 'First product',
'avg_price' => ['$avg' => "price"]
]);
})