本文介绍了按日期在laravel mongodb中分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongo和laravel.我通常在30天的时间内获取数据.我想按天分组数据.我试过 $ project $ dayOfMonth 并按 day 分组,但是按月的天数对它们进行分组,我希望在在此期间的天数.有办法吗?

I'm using mongo and laravel.I'm getting data in periods of time, usually 30 days. I want to group the data by day. I've tried $project $dayOfMonth and group by day but it grouping them in order of days in month and I want to be ordered in days in the period.is there a way?

[
     '$match' => [
           "created_at" => [
               '$gte' => new \MongoDB\BSON\UTCDateTime($thisMonth),
                        ]
                    ],
                ],
                    [
      '$project' => [
              'day' => [
              '$dayOfMonth' => [
              'date' => '$created_at',
               ]
         ],
      ]

 ],
 [
      '$group' => [
                 '_id' => '$day',
                  'count' => ['$sum' => 1],
          ],

 ],

样本:

  {#940
  flag::STD_PROP_LIST: false
  flag::ARRAY_AS_PROPS: true
  iteratorClass: "ArrayIterator"
  storage: array:16 [
    "_id" => ObjectId {#933
      +"oid": "5b2ff00e35826377be16ff82"
    }
    "orderNumber" => "10000"
    "userName" => "dGFraHRlLTkwMDQ2NDcyOJRbugaZlHWdMR+nCNzaUfY="
    "updated_at" => UTCDateTime {#938
      +"milliseconds": "1529868539000"
    }
    "created_at" => UTCDateTime {#939
      +"milliseconds": "1529868302000"
    }
  ]
}

推荐答案

您可以使用 $ dateFromString 可以根据所需的格式将日期对象转换为字符串.

You can use $dateFromString to converts a date object to a string according to a your desired format.

[ "$match" => [
  "created_at" => [ '$gte' => new \MongoDB\BSON\UTCDateTime($thisMonth) ]
]],
[ "$group" => [
  "_id" => [ "$dateToString" => [ "format" => "%Y-%m-%d", "date" => "$created_at" ] ],
  "count" => [ "$sum" => 1 ]
]]

这篇关于按日期在laravel mongodb中分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 03:23