如何在 MongoDB 中返回具有最新日期的元素 [英] How to return elements with the most recent date in MongoDB

查看:44
本文介绍了如何在 MongoDB 中返回具有最新日期的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MongoDB 上,如何从此列表中选择具有最新日期的元素:

On MongoDB, how can I select elements with the most recent date from this list :

[{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d55"),
"Date" : "12-09-2018",
"Type" : "A",
"Value" : 73650.14
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d15"),
"Date" : "12-09-2018",
"Type" : "B",
"Value" : 73650.14
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d58"),
"Date" : "13-09-2018",
"Type" : "A",
"Value" : 80000
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d56"),
"Date" : "13-09-2018",
"Type" : "B",
"Value" : 800000
}]

为了获得这个列表:

[{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d58"),
"Date" : "13-09-2018",
"Type" : "A",
"Value" : 80000
},
{
"_id" : ObjectId("5c5064f39d0c4b52cf6d1d56"),
"Date" : "13-09-2018",
"Type" : "B",
"Value" : 800000
}]

这可能很容易,但尽管进行了很多研究,我还是无法做到.我试图用 $group 操作符来实现,但我从来没有找到如何推送所需的值(我只得到了日期或没有任何过滤器的所有元素).

It is probably easy but I just cannot make it despite many researches. I tried to make it with the $group operator but I have never found how to push the desired values (either I only got the Date or all elements without any filter).

我是 Mongo DB 的新手,非常感谢您的帮助.

I am new on Mongo DB and I would really appreciate your help.

谢谢

推荐答案

以下 MongoDB 3.6 查询向每个文档添加一个新的日期字段,按该字段分组并将该组中的文档推送到数组中,按 _id 排序(date) 降序,限制到第一个文档(最近的日期),展开文档数组,然后通过替换每个文档的根并投影原始字段来清理结果.

The following query for MongoDB 3.6 adds a new date field to each document, groups by that field and pushes documents in that group into an array, sorts by the _id (date) in descending order, limits to the first document (most recent date), unwinds the array of documents, and then cleans up result by replacing the root of each document and projecting the original fields.

db.colx.aggregate([{
  $addFields: {
    ISODate: {
      $dateFromString: {
        dateString: "$Date"
      }
    }
  }
}, {
  $group: {
    _id: "$ISODate", 
    items: {
      $push: "$$ROOT"
    }
  }
}, {
  $sort: {
    _id: -1
  }
}, {
  $limit: 1
}, {
  $unwind: "$items"
}, {
  $replaceRoot: {
    newRoot: "$items"
  }
}, {
  $project: {
    _id: 1, 
    Date: 1, 
    Type: 1, 
    Value: 1
  }
}])

输出:

{ "_id" : ObjectId("5c5064f39d0c4b52cf6d1d58"), "Date" : "13-09-2018", "Type" : "A", "Value" : 80000 }
{ "_id" : ObjectId("5c5064f39d0c4b52cf6d1d56"), "Date" : "13-09-2018", "Type" : "B", "Value" : 800000 }

这篇关于如何在 MongoDB 中返回具有最新日期的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆