按日、月、年获取不同的 ISO 日期

Get distinct ISO dates by days, months, year

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

例如,如果文档有日期:

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

架构片段:

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

我尝试对模式字段使用 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")

所以问题是:


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

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
}
   }
])

实际上,您可以通过 $group/_id: null/$addToSet 阶段区分值。

我还在这里使用 dateToString 将您的日期格式化为 "%Y-%m"(例如 2021-12)。

// { date: ISODate("2021-12-05") }
// { date: ISODate("2021-12-08") }
// { date: ISODate("2022-04-05") }
// { date: ISODate("2022-12-14") }
db.collection.aggregate([
  { $group: {
    _id: null,
    months: { $addToSet: { $dateToString: { date: "$date", format: "%Y-%m" } } }
  }}
])
// { _id: null, months: ["2021-12", "2022-04", "2022-12"] }