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

查看:154
本文介绍了获取不同的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

  • 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

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

模式片段:

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

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

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'...)

  • a: How can I accomplish the above?
  • b: Is it possible to specify which part of the date you want distinct? Like distinct('date.month'...)?

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

I've found u 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天全站免登陆