按天、月、年获取不同的 ISO 日期 [英] Get distinct ISO dates by days, months, year

查看:18
本文介绍了按天、月、年获取不同的 ISO 日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 MongoDB 中的所有文档对象获取一组不同的年份和月份.

I want to get a distinct set of years and months for all document objects in my MongoDB.

例如,如果文档有日期:

For example, if documents have dates:

  • 2015/08/11
  • 2015/08/11
  • 2015/08/12
  • 2015/09/14
  • 2014/10/30
  • 2014/10/30
  • 2014/08/11

返回所有文档的唯一月份和年份,例如:

Return unique months and years for all documents, ex:

  • 2015/08
  • 2015/09
  • 2014/10
  • 2014/08

架构片段:

var myObjSchema = mongoose.Schema({
        date: Date,
        request: {
           ...

我尝试对模式字段 date 使用 distinct:

I tried using distinct against schema field date:

db.mycollection.distinct('date', {}, {})

但这给出了重复的日期.输出片段:

But this gave duplicate dates. Output snippet:

ISODate("2015-08-11T20:03:42.122Z"),
ISODate("2015-08-11T20:53:31.135Z"),
ISODate("2015-08-11T21:31:32.972Z"),
ISODate("2015-08-11T22:16:27.497Z"),
ISODate("2015-08-11T22:41:58.587Z"),
ISODate("2015-08-11T23:28:17.526Z"),
ISODate("2015-08-11T23:38:45.778Z"),
ISODate("2015-08-12T06:21:53.898Z"),
ISODate("2015-08-12T13:25:33.627Z"),
ISODate("2015-08-12T14:46:59.763Z")

所以问题是:

  • a:我怎样才能完成上述任务?
  • b: 是否可以指定日期的哪一部分需要区分?喜欢 distinct('date.month'...)?

我发现您可以通过以下查询获得这些日期等,但结果并不明显:

I've found you can get these dates and such with the following query, however the results are not distinct:

db.mycollection.aggregate( 
     [ 
         { 
             $project : { 
                  month : { 
                      $month: "$date" 
                  }, 
                  year : { 
                      $year: "$date" 
                  }, 
                  day: { 
                      $dayOfMonth: "$date" 
                  } 
              }
          } 
      ] 
  );

输出:重复

{ "_id" : "", "month" : 7, "year" : 2015, "day" : 14 }
{ "_id" : "", "month" : 7, "year" : 2015, "day" : 15 }
{ "_id" : "", "month" : 7, "year" : 2015, "day" : 15 }

推荐答案

您需要在投影后对文档进行分组并使用 $addToSet 累加器运算符

You need to group your document after the projection and use $addToSet accumulator operator

db.mycollection.aggregate([
    { "$project": { 
         "year": { "$year": "$date" }, 
         "month": { "$month": "$date" } 
    }},
    { "$group": { 
        "_id": null, 
        "distinctDate": { "$addToSet": { "year": "$year", "month": "$month" }}
    }}
])

这篇关于按天、月、年获取不同的 ISO 日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆