我怎样才能按照Array中最后一项的时间过滤记录

时间:2015-09-17 11:40:40

标签: mongodb

每条记录都有历史数组,如何才能获得历史记录中项目'updated_at'时间应该> = 3小时前的最后一项?

我希望在aggregation

中的预处理步骤之后执行此过滤
collection.aggregate(
      {"$match" => match_cond},

      ....

由于

文件格式

  "price": 2988.0,
  "history": [
    {
      "updated_at": new Date(1441469169200),
      "price": 2988
    },
    {
      "updated_at": new Date(1441620011237),
      "price": 1558
    },
    {
      "updated_at": new Date(1441621596776),
      "price": 2988
    },
    {
      "updated_at": new Date(1441625059995),
      "price": 1558
    },
    {
      "updated_at": new Date(1441689121096),
      "price": 2988
    },
    {
      "updated_at": new Date(1441690782988),
      "price": 1558
    },
    {
      "updated_at": new Date(1441695110834),
      "price": 2988
    }
  ],

1 个答案:

答案 0 :(得分:0)

执行$展开,然后在必要时重新组合。

collection.aggregate( [
    { $unwind: "history" },
    { 
       $match: { 
          "history.updated_at" : {
                $gt: ISODate("2015-09-17T10:00:00Z")
          }
       } 
    },
    { $group: { 
         _id : { 
             _id : "$_id",
             [ any fields except history ]
         },
         last_updated: { $last : "$history.updated_at"},
         last_price: { $last : "$history.price"}
     }} 
])