MongoDB group by dan count (MySQL dan PHP)

Bismillaahirrohmaanirrohiim…

Pada MySQL, untuk menjalankan query group by dan count atau sum caranya cukup mudah, bisa dengan query di bawah ini:

select kolomA, count(kode) as jumkode from tabel where status='oke' group by kolomA order by jumkode DESC 

Jika pada mongoDB, menggunakan fungsi aggregate

 db.namacollection.aggregate([{ $match: { status: "oke" } },{"$group": {_id: "$kolomA",count: {$sum: 1}}},{$sort: {count: -1}}])

Jika menggunakan php driver mongoDB, perintahnya seperti berikut

$manager = new MongoDB\Driver\Manager();
$command = new MongoDB\Driver\Command([
  'aggregate' => 'namacollection',
  'pipeline' => [
      ['$match'=>['status'=>'oke']],
      ['$group' => ['_id' => '$kolomA', 'count' => ['$sum' => 1]]],
      ['$sort'=>['count'=>-1]],
  ],
  'cursor' => new stdClass,
]);

$cursor = $manager->executeCommand('namadatabase', $command);

Nah, sekarang jika ingin memberi filter range tanggal dari tanggal sekian sampai tanggal sekian, perintah di mongoDB nya sebagai berikut:

db.namacollection.aggregate([{ $match: { tanggal: {$gte:ISODate("2021-05-01"),$lt:ISODate("2020-05-30"}} } },{"$group": {_id: "$kolomA",count: {$sum: 1}}},{$sort: {count: -1}}])
//$gte bisa diganti $gt kalau error

Versi phpnya adalah seperti di bawah ini:

$manager = new MongoDB\Driver\Manager();
$command = new MongoDB\Driver\Command([
  'aggregate' => 'namacollection',
  'pipeline' => [
  	['$match'=>['tanggal'=>
                    [
                        '$gt'=>new MongoDB\BSON\UTCDatetime(strtotime('2021-05-01 00:00:00') * 1000),
                        '$lt'=>new MongoDB\BSON\UTCDatetime(strtotime('2020-05-30 23:59:59') * 1000),
                    ] 
                   ]
        ],
      ['$group' => ['_id' => '$kolomA', 'count' => ['$sum' => 1]]],
      ['$sort'=>['count'=>-1]],
  ],
  'cursor' => new stdClass,
]);

$cursor = $manager->executeCommand('namadatabase', $command);
//format kolom tanggal haruslah berupa datetime

Demikian, semoga bermanfaat…

Baca Juga:   Membersihkan log mongodb yang besar

Bagikan

You May Also Like

About the Author: rasupe

Leave a Reply

Your email address will not be published. Required fields are marked *