【问题标题】:MongoDB query documents having a latest value of a field and keeping other fieldsMongoDB查询文档具有一个字段的最新值并保留其他字段
【发布时间】:2020-12-15 23:17:50
【问题描述】:

假设我在 mongo 中有这个架构文档:

{
    "_id" : ObjectId("asd9024380s"),
    "timestamp" : 1581407619976,
    "value" : 5,
    "typeId" : ObjectId("lkjdsa08934"),
    "unitId" : ObjectId("ce234890")
}

首先,我只想考虑具有abcunitId 的文档。其中,对于每个typeId,我只想检索最新的一个(timestamp 最高的那个)。

假设集合是这样的:

_id timestamp value typeId unitId
1 20 3 "ff" "abc"
2 17 2 "ff" "fff"
3 18 3 "gg" "abc"
4 21 5 "gg" "fff"
5 15 4 "ff" "abc"
6 24 2 "gg" "abc"

我想得到:

_id timestamp value typeId unitId
1 20 3 "ff" "abc"
6 24 2 "gg" "abc"

我正在使用这个查询:

db.observations.aggregate(
   [
     { $match: {"unitId": "abc",
     { $sort: { "typeId": 1, "timestamp": 1 } },
     {
       $group:
         {
           _id: "$typeId",
           lastSalesDate: { $last: "$timestamp" }
         }
     }
])

但这仅检索timestamptypeId 的字段,而我也对其他字段感兴趣,尤其是value,并且作为一个聚合我不确定我是否将其修改为也包含value

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以使用$$ROOT 获取完整对象,

    {
      latestRecord: { $last: "$$ROOT" }
    }
    

    Playground

    你可以获取指定字段名称的必填字段,

    {
      latestRecord: { 
        $last: {
           _id: "$_id",
           timestamp: "$timestamp",
           alue: "$value"
        } 
      }
    }
    

    Playground

    【讨论】:

      【解决方案2】:

      尝试使用“投影”。例如:

      db.observations.aggregate(
         [
           { $project: { "typeId": 1, "timestamp": 1, "value": 1 } },
           { $match: {"unitId": "abc"}},
           { $sort: { "typeId": 1, "timestamp": 1 } },
           {
             $group:
               {
                 _id: "$typeId",
                 lastSalesDate: { $last: "$timestamp" }
               }
           }
      ])
      

      【讨论】:

        猜你喜欢
        • 2020-05-06
        • 2019-05-11
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 2019-09-08
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        相关资源
        最近更新 更多