如何通过jenssegers将MongoDB聚合查询转换为Laravel MongoDB [英] How to convert MongoDB aggregation query to Laravel MongoDB by jenssegers

查看:902
本文介绍了如何通过jenssegers将MongoDB聚合查询转换为Laravel MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 changes 的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"
}

然后,我想进行典型的SQL查询以计算出现次数,并按field进行分组.因此,我已经在MongoDB中创建了查询

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++;
    },
});

它可以正常工作,但如何将其转换为可与Laravel 4一起使用?我正在使用jenssegers/laravel-mongodb与mongo服务器通信.

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.

此外,我在查询中还有更多条件,为了使我的问题看起来更清楚,已删除了这些条件,因此我正在寻找一种解决方案,以将该查询准确地转换为laravel,而不是其他可能的解决方案:).

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 :).

推荐答案

使用聚合框架方法不仅效果更好,而且还可以使用底层驱动程序提供的原始MongoDB集合对象.尝试翻译语法是一个更好的选择:

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
                )
            )
        )   
    ));
});

结果与.group()之类的方法略有不同,但是它使用MongoDB服务器上的本机代码,并且不像.group()方法实际那样依赖JavaScript解释,实际上是mapReduce的包装器

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.

因此,请使用本机MongoDB方式以获得最佳性能.

So use the native MongoDB way for the best performance.

这篇关于如何通过jenssegers将MongoDB聚合查询转换为Laravel MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆