以日期,月份,年份获取不同的ISO日期

问题描述:

我想为我的MongoDB中的所有文档对象获取一组不同的年份和月份。以日期,月份,年份获取不同的ISO日期

例如,如果文档有日期:

  • 2015年8月11日
  • 2015年8月11日
  • 2015年8月12日
  • 2015年9月14日
  • 2014/10/30
  • 2014/10/30
  • 2014/08/11

返回独特的几个月和几年的所有文件,例如:

  • 2015/08
  • 2015/09
  • 十分之二千零十四
  • 2014/08

模式代码段:

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

我尝试使用distinct对架构领域date

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

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

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") 

所以,问题是:

  • 一:我怎样才能完成上述?
  • b:是否可以指定你想要区分哪一部分日期?像distinct('date.month'...)

编辑:我发现u能得到这些日期,例如用下面的查询,但结果并不明显:

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累加器运算符

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

db.mycollection.aggregate(
[ 
{ 
"$project": { 
        "year": { "$year": "$date" }, 
        "month": { "$month": "$date" } 
      } 
},{ $group : { 
        "_id" :{"year" : "$year" } 
       } 
}, 
{ 
$sort: {'_id': -1 
} 
    } 
])