2015-11-10 52 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將範圍在一個聚合。 –