【问题标题】:GroupBy date + mongodbGroupBy 日期 + MongoDB
【发布时间】:2018-10-08 05:47:02
【问题描述】:

我必须根据给定文档的月份汇总结果。将以下内容视为我的文档:

{
    "_id" : ObjectId("5b3314a12b05b1b247366f48"),
    "email" : "abc@gmail.com",
    "qwerty":[{
            "id" : "5ba4ebbad1b5eaf038841302",
            "status" : "inprogress",           
            "Date" : "2018-08-20"
        }, 
        {
            "id" : "5ba4ebbad1b5eaf038841303",
            "status" : "inprogress",           
            "Date" : "2018-08-20"
        }]

以下是我的查询:

var query =[
        { $match: {"email":email} },
        {$unwind: "$courses" },
        {$group:{_id:{$substrCP: ["$qwerty.Date", 5, 2]},count:{$sum:1}}}
    ];

它工作正常。但是我$substrCP: ["$qwerty.Date", 5, 2]基于日期格式是“2018-08-20”,如果是“20-08-2018”呢?因此,可以将上述查询更改为适应非类型。

我也尝试使用新的Date("").getMonth(),但它显示为“NaN”,我知道它不可能在组内使用。

请提出你的想法。

【问题讨论】:

标签: node.js mongodb group-by


【解决方案1】:

您可以结合使用$month$dateFromString 来获得您需要的东西:

db.collection.aggregate([
  {
    $match: {
      "email": "abc@gmail.com"
    }
  },
  {
    $unwind: "$qwerty"
  },
  {
    $group: {
      _id: {
        $month: {
          $dateFromString: {
            dateString: "$qwerty.Date"
          }
        }
      },
      count: {
        $sum: 1
      }
    }
  }
])

您可以see it here 使用两种不同的日期格式。

要按日期分组,您可以不使用$month

db.collection.aggregate([
  {
    $match: {
      "email": "abc@gmail.com"
    }
  },
  {
    $unwind: "$qwerty"
  },
  {
    $group: {
      _id: {
        $dateFromString: {
          dateString: "$qwerty.Date"
        }
      },
      count: {
        $sum: 1
      }
    }
  }
])

查看这个版本here

【讨论】:

  • 感谢它的工作.. 但是如果我将 $month 更改为 $dateit throwing error $date is not recognized
  • 你为什么要这样做?在您的问题中,您是否使用月份没有?
  • 我需要 month 广告 date 作为单独的聚合查询。一个月它与您的帖子完美配合,但日期不是??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多