MongoDB Mongoose在默认的createdAt timestamp中按日期分组的日期

时间:2019-10-24 10:03:30

标签: javascript node.js mongodb mongoose

我有一个称为Session的模型。它具有id,设备和Mongoose默认时间戳。就是这样。

{
    _id: 5da977e431e58d4e7fc1da1c,
    device: 'Galaxy M10',
    createdAt: 2019-10-18T08:29:24.498Z,
    updatedAt: 2019-10-18T08:32:10.768Z,

  }

我想按createdAt日期将此会话分组。所以我尝试了这个。

const data = await db.Session.aggregate([
      { $match: { createdAt: { $gte: date } } },
      {
        $group: {
          _id: "$createdAt" ,
          count: { $sum: 1 }
        }
      }
    ]);

我得到的结果是这个

{ _id: 2019-10-17T11:32:49.346Z, count: 1 },
  { _id: 2019-10-18T07:14:45.695Z, count: 1 },
  { _id: 2019-10-17T10:49:35.434Z, count: 1 },
  { _id: 2019-10-18T08:17:05.999Z, count: 1 },
  { _id: 2019-10-17T09:56:53.574Z, count: 1 },
  { _id: 2019-10-18T07:14:15.154Z, count: 1 },
  { _id: 2019-10-18T07:07:19.346Z, count: 1 },
  { _id: 2019-10-18T07:13:57.720Z, count: 1 },
  { _id: 2019-10-17T13:09:17.721Z, count: 1 },
  { _id: 2019-10-18T07:31:59.900Z, count: 1 },
  { _id: 2019-10-18T08:29:24.498Z, count: 1 },
  { _id: 2019-10-18T08:05:54.339Z, count: 1 }

我的排除结果是

  { _id: 2019-10-18, count: 8 },
  { _id: 2019-10-17, count: 4 },

如果这是基于SQL而不是group by createdAt,则我执行group by Date(createdAt)。但是我该如何在MongoDB中做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以通过从日期中提取“ dayOfMonth”,“月”和“年”并按三个组进行分组来实现。查询将变为:

protected function _beforeSave()
    {
        die('something');
        parent::_beforeSave();
        if (!$this->getOrderId() && $this->getOrder()) {
            $this->setOrderId($this->getOrder()->getId());
        }
        if ($this->getParentItem()) {
            $this->setParentItemId($this->getParentItem()->getId());
        }
        return $this;
    }