I need to get result of following query in laravel frame work (used jenssegers library)
db.product.aggregate({ $group : {_id : "$catid", total : { $sum : 1}}},
{$sort:{total:-1}});
I tried to do this like this
return DB::connection($this - > connection)- >
collection($this - > collection) - > aggregate(
'{ $group : {_id : "$catid", total : { $sum : 1 }}},{$sort:{total:-1}}'');
But it is giving error like "ErrorException Undefined index: aggregate" need to know that how to use mongodb "db.collection.aggregate"
The document of my collection is like this
{
"_id": ObjectId("5369d68611fe14ddc5f59ff9"),
"sku": 123456,
"productid": 1,
"name": "name1",
"catid": 1
}
In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.
The MongoDB aggregation framework is an extremely powerful set of tools. The processing is done on the server itself which results in less data being sent over the network.
Can I Use MongoDB With Laravel? Yes! In fact, MongoDB is a great choice for Laravel projects. As we get started with Laravel development using MongoDB, we'll work through an example of how to build a blog application.
You can access the aggregate method on the Jenssegers library via the raw()
function.
Here is an example of an aggregate call with group, sort, limit and project. You can adapt it to your needs:
//Perform an aggregate function and get a cursor
$cursor = Data::raw()->aggregate([
['$group' =>
['_id' => '$name', 'count' => ['$sum' => 1]]
],
['$sort' => ['count' => -1]],
['$limit' => 30],
['$project' => ['_id' => 0,
'text' => '$_id',
'size' => '$count',
]
],
]);
//Iterate your cursor
$current = $cursor;
do {
echo $current; //Process each element
} while (!($current = $cursor->next()));
Note that using the raw()
method requires using a cursor because it is a low-level call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With