首页 > 解决方案 > 从 mongo 集合中获取月份的最后一个条目

问题描述

以以下格式说出集合存储数据。每天都会在集合中添加一个新条目。日期采用 ISO 格式。

|id|dt|data|
---
|1|2021-03-17|{key:"A", value:"B"}
...
|1|2021-03-14|{key:"A", value:"B"}
...
|1|2021-02-28|{key:"A", value:"B"}
|1|2021-02-27|{key:"A", value:"B"}
...
|1|2021-02-01|{key:"A", value:"B"}
|1|2021-01-31|{key:"A", value:"B"}
|1|2021-01-30|{key:"A", value:"B"}
...
|1|2021-01-01|{key:"A", value:"B"}
|1|2020-12-31|{key:"A", value:"B"}
...
|1|2020-11-30|{key:"A", value:"B"}
...

我需要有关查询的帮助,该查询为我提供给定时间段内每个月的最后一天。下面是我能够执行的查询,它没有给出当月的最后一天,因为我按日、月和年对其进行排序。

db.getCollection('data').aggregate([
    {
      $match: {dt: {$gt: ISODate("2020-01-01")}
    },
    {
      $project: {
        dt: "$dt",
        month: {
          $month: "$dt"
        },
        day: {
          $dayOfMonth: "$dt"
        },
        year: {
          $year: "$dt"
        },
        data: "$data"
      }
    },
    {
        $sort: {day: -1, month: -1, year: -1}
    },
    { $limit: 24},
    {
        $sort: {dt: -1}
    },
])

我追求的结果是:

|1|2021-03-17|{key:"A", value:"B"}
|1|2021-02-28|{key:"A", value:"B"}
|1|2021-01-31|{key:"A", value:"B"}
|1|2020-12-31|{key:"A", value:"B"}
|1|2020-11-30|{key:"A", value:"B"}
...
|1|2020-01-31|{key:"A", value:"B"}

标签: mongodbaggregate

解决方案


按年和月对记录进行分组,获取该月的最大日期。

db.getCollection('data').aggregate([
    { $match: { dt: { $gt: ISODate("2020-01-01") } } },
    { $group: { // group by
      _id: { $substr: ['$dt', 0, 7] }, // get year and month eg 2020-01
      dt: { $max: "$dt" }, // find the max date
      doc:{ "$first" : "$$ROOT" } } // to get the document
    },
    { "$replaceRoot": { "newRoot": "$doc"} }, // project the document
    { $sort: { dt: -1 } }
]);

$substr

$组

$replaceRoot

$最大

第一美元


推荐阅读