2015-11-10 53 views
0

我有这个文件,每一个工具:Mongoid查询嵌入文档,并且返回父

{ 
    "_id" : ObjectId("54da43aea96ddcc40915a457"), 
    "checked_in" : false, 
    "barcode" : "PXJ-234234", 
    "calibrations" : [ 
     { 
      "_id" : ObjectId("54da46ec546173129d810100"), 
      "cal_date" : null, 
      "cal_date_due" : ISODate("2014-08-06T00:00:00.000+0000"), 
      "time_in" : ISODate("2015-02-10T17:46:20.250+0000"), 
      "time_out" : ISODate("2015-02-10T17:46:20.250+0000"), 
      "updated_at" : ISODate("2015-02-10T17:59:08.796+0000"), 
      "created_at" : ISODate("2015-02-10T17:59:08.796+0000") 
     }, 
     { 
      "_id" : ObjectId("5509e815686d610b70010000"), 
      "cal_date_due" : ISODate("2015-03-18T21:03:17.959+0000"), 
      "time_in" : ISODate("2015-03-18T21:03:17.959+0000"), 
      "time_out" : ISODate("2015-03-18T21:03:17.959+0000"), 
      "cal_date" : ISODate("2015-03-18T21:03:17.959+0000"), 
      "updated_at" : ISODate("2015-03-18T21:03:17.961+0000"), 
      "created_at" : ISODate("2015-03-18T21:03:17.961+0000") 
     }, 
     { 
      "_id" : ObjectId("5509e837686d610b70020000"), 
      "cal_date_due" : ISODate("2015-03-18T21:03:51.189+0000"), 
      "time_in" : ISODate("2015-03-18T21:03:51.189+0000"), 
      "time_out" : ISODate("2015-03-18T21:03:51.189+0000"), 
      "cal_date" : ISODate("2015-03-18T21:03:51.189+0000"), 
      "updated_at" : ISODate("2015-03-18T21:03:51.191+0000"), 
      "created_at" : ISODate("2015-03-18T21:03:51.191+0000") 
     } 
    ], 
    "group" : "Engine", 
    "location" : "Here or there", 
    "model" : "ZX101C", 
    "serial" : NumberInt(15449), 
    "tool" : "octane analyzer", 
    "updated_at" : ISODate("2015-09-30T20:43:55.652+0000"), 
    "description" : "Description...", 
} 

工具要定期校准。我想要做的是抓住本月到期的工具。

目前,我的查询是这样的:

scope :upcoming, -> { where(:at_ats => false).where('calibrations.0.cal_date_due' => {'$gte' => Time.now-1.day, '$lte' => Time.now+30.days}).order_by(:'calibrations.cal_date_due'.asc) }

然而,这个查询获取第一校准目标的工具,它需要是最后一次。我尝试了无数的东西,但我被困在这里。

如何确保我查询的是最新的校准文档,而不是第一个(这将是最古老的,因此不相关)?

回答

1

你应该看看aggregation framework$unwind运营商。

This link may be help。 此链接可能会有所帮助。它包含了一个使用'聚合框架'来获取数组的最后一个元素的例子,也就是你最近的例子。

+0

是的,我同意。你能提供一个特定的解决方案?我不觉得这个答案直接解决了我的问题。 –

+0

好的,这是汇总的查询来获取上次日期:'db.getCollection('tools')。aggregate([ {$ unwind:“$ calibrations”}, {$ group:{_id:“$ _id”, last_date:{$ last:“$ calibrations.cal_date_due”}}}' – hecnabae

+0

看起来不错。现在我需要做的是在30天内过滤文件。另外,我如何使结果成为一个轨道对象?我试图让这个范围,但我不认为mongoid将范围在一个聚合。 –