How to convert MongoDB aggregation query to Laravel MongoDB by jenssegers

前端 未结 2 754
悲哀的现实
悲哀的现实 2020-12-31 22:12

I have MongoDB collection called changes which contains following data

{
    \"date\" : ISODate(\"2014-06-09T00:00:00.000Z\"),
    \"field\"         


        
相关标签:
2条回答
  • 2020-12-31 22:52

    Even if it's an question, there's an unseful entry in the repository wiki: Complex aggregate call

    Hope it may help other people like me ;)

    0 讨论(0)
  • 2020-12-31 23:05

    You are both better off using the aggregation framework methods and also diving into the raw MongoDB collection object provided from the underlying driver to do so. It's a much better option that trying to translate the syntax:

    // Returns the original Mongo Result
    $result = DB::collection('changes')->raw(function($collection)
    {
        return $collection->aggregate(array(
            array(
                '$group' => array(
                    '_id' => '$field',
                    'count' => array(
                        '$sum' => 1
                    )
                )
            )   
        ));
    });
    

    The result is a little different from the result of a method like .group() but this uses native code on the MongoDB server and does not rely on JavaScript interpretation like the .group() method actually does, being really a wrapper around mapReduce.

    The end result is much faster, and also generally more efficient than you will get out of the native framework interface.

    So use the native MongoDB way for the best performance.

    0 讨论(0)
提交回复
热议问题