dse55384 2014-06-10 13:57
浏览 429
已采纳

如何通过jenssegers将MongoDB聚合查询转换为Laravel MongoDB

I have MongoDB collection called changes which contains following data

{
    "date" : ISODate("2014-06-09T00:00:00.000Z"),
    "field" : "ip",
    "from" : "157.11.209.123",
    "to" : "107.21.109.254"
}
{
    "date" : ISODate("2014-05-15T00:00:00.000Z"),
    "field" : "ip",
    "from" : "107.21.109.254",
    "to" : "157.11.209.123"
}
{
    "date" : ISODate("2014-06-09T00:00:00.000Z"),
    "field" : "registration",
    "from" : "Old service",
    "to" : "Some new service"
}

Then I want to make typical SQL query that counts occurrences and group it by field. So, I've created query in MongoDB

db.changes.group({
    "key": {
        "field": true
    },
    "initial": {
        "count": 0,
    },
    "reduce": function(obj, prev) {
            prev.count++;
    },
});

It works fine but how can I convert it to works with Laravel 4? I am using jenssegers/laravel-mongodb to communicate with mongo server.

In addition, I have more conditions in query, which I've removed to make my question looks more clearly, so I'm looking for solution to convert exactly that query into laravel, not other possible solutions :).

  • 写回答

1条回答 默认 最新

  • douciping4283 2014-06-10 14:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts绘制图表
  • ¥15 请教两个关于高德地图定位不准的技术问题
  • ¥15 根据企业名称 对照两个文件 样本筛选/匹配
  • ¥15 Linux环境下CA证书更新问题
  • ¥15 sqlserver语句提取结果以外数据
  • ¥60 微信小程序如何上传QQ聊天文件
  • ¥300 开发的系统遭到无良商家的破解,请问如何防止再次发生,并追回损失
  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel