0

私はMongoDbを初めて使用し、MapReduceまたはAggregationの仕事をしています(おそらく)。

この形式のドキュメントを含む「請求書」コレクションがあります。

{
    date: 'some unix timestamp',
    total: 12345,
    paid: true
}

月(jan-dec)を列として、各年の行を、その月の合計(有料と未払いで割ったもの)をセルに表示する必要があります。このような:

     |     Jan     |      Feb      | ...
2013 | 1,222 / 200 |  175 / 2,122  | ...
...

mongoコマンドを正しく取得するのを手伝ってもらえますか?たぶん私はmongoで実行するためにいくつかのJSコードを書くほうがいいですか?

4

2 に答える 2

4

MapReduceを使用した解決策を見つけました。ここでは、PHPから使用されています。

$map = new MongoCode('
    function() {
        var d = new Date(this.date*1000);
        emit({y: d.getFullYear(), m: d.getMonth()}, {
            total: this.total,
            notPaid: this.paid ? 0 : this.total,
            count: 1
        });
    };
');

$reduce = new MongoCode('
    function(month, values) {
        result = { total: 0, notPaid: 0, count: 0 };
        for (var i = 0; i < values.length; i++) {
            result.total += values[i].total;
            result.notPaid += values[i].notPaid;
            result.count += values[i].count;
        }
        return result;
    };
');

$result = $db->command(array(
    'mapreduce' => 'invoices',
    'map' => $map,
    'reduce' => $reduce,
    'out' => 'temp'
));

echo $result['timeMillis'];

これで、結果は「temp」コレクションに含まれ、月に1つのドキュメントになります。最適化または強化できますか?

于 2013-01-08T20:35:42.377 に答える
3

これは、次のような集約フレームワークを使用して実行できます。

db.invoices.aggregate( [
    {
        "$project" : {
            "yr" : {
                "$year" : "$date"
            },
            "mo" : {
                "$month" : "$date"
            },
            "total" : 1,
            "unpaid" : {
                "$cond" : [
                    "$paid",
                     0,
                    "$total"
                ]
            }
        }
    },
    {
        "$group" : {
            "_id" : {
                "y" : "$yr",
                "m" : "$mo"
            },
            "total" : {
                "$sum" : "$total"
            },
            "unpaid" : {
                "$sum" : "$unpaid"
            }
        }
    }
] )

最後に別のものを使用$projectして出力をきれいにし、$sortそれを注文することができますが、それがその基本的な機能コアです。

于 2013-01-09T02:18:43.473 に答える