按天,月,年获取不同的ISO日期

Gro*_*ler 4 date mongodb aggregation-framework

我想为MongoDB中的所有文档对象分别设置几年和几个月的时间。

例如,如果文档有日期:

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

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

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

模式片段:

var myObjSchema = mongoose.Schema({
        date: Date,
        request: {
           ...
Run Code Online (Sandbox Code Playgroud)

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

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

但这给出了重复的日期。输出代码段:

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")
Run Code Online (Sandbox Code Playgroud)

所以问题是:

  • 答:我怎样才能做到以上几点?
  • b:是否可以指定您要区分日期的哪一部分?喜欢distinct('date.month'...)吗?

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

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

输出:重复

{ "_id" : "", "month" : 7, "year" : 2015, "day" : 14 }
{ "_id" : "", "month" : 7, "year" : 2015, "day" : 15 }
{ "_id" : "", "month" : 7, "year" : 2015, "day" : 15 }
Run Code Online (Sandbox Code Playgroud)

sty*_*ane 8

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

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