group by date in laravel mongodb

China☆狼群 提交于 2021-01-27 21:31:50

问题


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],
          ],

 ],

sample:

  {#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"
    }
  ]
}

回答1:


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 ]
]]


来源:https://stackoverflow.com/questions/51230104/group-by-date-in-laravel-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!