Mongoid 查询嵌入文档和 return 父级

Mongoid query embedded document and return parent

我有这个文档,每一个都是一个工具:

{ 
    "_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) }

但是,此查询通过第一个校准对象获取工具,并且它需要是最后一个。我已经尝试了无数的东西,但我被困在这里。

如何确保查询的是最新的校准文档,而不是第一份(最旧的,因此不相关)?

您应该查看 aggregation framework and $unwind 运算符。

这个link可能会有帮助。 这 link 可能会有帮助。它包含一个使用 'aggregation framework' 获取数组最后一个元素的示例,即您的案例中的最新元素。