How to execute aggregate in mongodb in laravel framework

后端 未结 2 1356
天命终不由人
天命终不由人 2021-01-05 07:51

I need to get result of following query in laravel frame work (used jenssegers library)

db.product.aggregate({ $group : {_id : \"$catid\", total : { $su         


        
相关标签:
2条回答
  • 2021-01-05 08:04

    You can access the aggregate method on the Jenssegers library via the raw() function.

    Here is a sample of a working random aggregate call that I use, 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.

    Hope it helps.

    0 讨论(0)
  • 2021-01-05 08:19

    try something like this

    db.product.aggregate(
         { "$group" : 
            { "_id" : "$catid", 
              "total" : { "$sum" : 1}
            }
         },
         { "$sort" : {"productid":-1} }
    );
    
    0 讨论(0)
提交回复
热议问题