0

我正在尝试匹配标准(cl = 1),然后按月汇总所有结果(我也尝试过年/月/日,但没有运气)。

当我运行下面的代码时,它似乎工作正常,输出显示月份等,但是没有添加任何统计信息。

Mongo 中的 $du 字段是一个 MongoDate 对象。

有谁知道我做错了什么?

有关按日期搜索并返回结果的代码片段,请参见最底部。

        $result = $collection->aggregate(
            array(
                array('$match' => array(
                    'cl' => $app_id) # application id, int such as "2"
                ),
                array('$project' => array(
                    //'year' => array('$year' => '$du'),
                    'month' => array('$month' => '$du'),
                    //'week' => array('$week' => '$du'),
                )),

                array('$group' => 
                    array(
                        '_id' => array(
                            'month' => '$month',
                        ),
                        'i' => array('$sum' => '$vs.i'),
                        'r' => array('$sum' => '$vs.r'),
                        'u' => array('$sum' => '$vs.u'),
                    )
                ),
                array(
                    '$sort' => array(
                        '_id' => -1
                    )
                ),
                array(
                  '$limit' => 14
                )
            )
        );

输出:

Array
(
    [result] => Array
        (
            [0] => Array
                (
                    [_id] => Array
                        (
                            [month] => 10
                        )

                    [i] => 0
                    [r] => 0
                    [u] => 0
                )

            [1] => Array
                (
                    [_id] => Array
                        (
                            [month] => 9
                        )

                    [i] => 0
                    [r] => 0
                    [u] => 0
                )
        .......

工作 - 按日期搜索

$start = new MongoDate(strtotime("2012-10-01 00:00:00"));
$end = new MongoDate(strtotime("2013-10-15 00:00:00"));
$cursor = $collection->find(array("du" => array('$gt' => $start, '$lte' => $end)));
while ($cursor->hasNext()) {
    $document = $cursor->getNext();
    print_r($document);exit;
}

# RESPONSE
Array
(
    [_id] => MongoId Object
        (
            [$id] => 51acbfd33dd49497848a8e5b
        )

    [cl] => 1
    [du] => MongoDate Object
        (
            [sec] => 1370275795
            [usec] => 0
        )

    [vs] => Array
        (
            [i] => 11
            [u] => 1
        )

)   
4

1 回答 1

1

统计数据不存在是因为您没有选择投影它们。Project 默认为您提供 _id,但必须指定您想要的任何其他内容。

你需要这样的东西而不是你当前的 $project:

array('$project' => array(
    'month' => array('$month' => '$du'),
    'vs' => 1
))
于 2013-10-09T20:50:15.893 回答