mongodb - 从 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"}
解决方案
按年和月对记录进行分组,获取该月的最大日期。
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 } }
]);
推荐阅读
- python - 在python中读取200000行的文本文件
- python - 根据枚举列表Python从列表中获取第一个和最后一个元素
- excel - 如何检查日期是否在excel中多行的两个数据范围之间
- java - 如何在短时间内显示导入的图像?
- c# - 如果连接未处于连接状态,.NET core angular 项目无法发送数据?
- android - 使用 Firebase 跟踪应用安装的推荐
- javascript - JavaScript 正则表达式过滤两个字符之间的文本
- css - Clearfix来自“”内容的白色背景
- python - Python 中的 threading.Timer -- 两个函数在变量标识上达成一致,但在值上不一致
- spring-batch - Spring批处理实例id重复键错误,尝试从#1开始