如何获取MongoDB集合中每天的最后一个文档? [英] How to get last document of each day in MongoDB collection?

查看:76
本文介绍了如何获取MongoDB集合中每天的最后一个文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型Entry,其中包含特定时间医院的详细信息.数据如下所示:

I have a model Entry to which includes details of a hospital at a particular time. The data looks like this:

{
  "_id": "5ef9c7337874820008c1a026",
  "date": 1593427763640,
  //... some data
  "hospital": {
    "_id": "5ef8d06630c364000840bb6d",
    "name": "City Hospital",
    //... some data
  },
}

我想获取按医院 ID 分组的每天的最后一个查询.在 MySQL 中,可以使用 INNER JOIN 来实现.我如何使用 MongoDB 做到这一点?

I want to get the last query of each day grouped by the hospital ID. In MySQL, it can be achieved using INNER JOIN. How can I do it using MongoDB?

推荐答案

给定一天,计算一天的开始和结束.这是用于过滤记录,$match

Given a day, calculate start and end of a day. This is to be used for filtering records, $match

start_of_day_ephocs=
end_of_day_ephocs=

聚合查询

按日期排序,按医院编号分组,并选择第一个文档

sort by date, Group by hospital id,and select first document

db.Entry.aggregate(
   [
    { "$match": { "date": {"$gte":start_of_day_ephocs,"$lte":end_of_day_ephocs }} },
    { "$sort": { "date": -1 } },
     {
       $group:
         {
           "_id": "$hospital._id",
           "last_document": { "$first": "$$ROOT" }
         }
     }
   ]
)

这篇关于如何获取MongoDB集合中每天的最后一个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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