【问题标题】:Mongoid max and embeded collectionsMongoid max 和嵌入式集合
【发布时间】:2014-03-21 06:07:04
【问题描述】:

我有一个收集报告嵌入提交

class Report
  embeds_many :submissions

class Submission
  embedded_in :report
  field :date_submitted, type: TimeWithZone
  field :mistakes, type: Integer

我正在尝试在报告上创建范围

我想添加一个包含两部分的范围查询 获取同样零错误的最新提交(由 max date_submitted 给出)

我可以为错误部分创建一个范围,但不知道如何获得最新的提交

scope :my_scope, where("submissions.mistakes" => 0)

所以这个报告将被返回,因为它最后一次输入提交的错误为零

Report
"submissions" : [
        {

            "date_submitted" : ISODate("2014-01-28T13:00:00Z"),
            "mistakes" : 11
        },
        {
            "date_submitted" : ISODate("2014-03-08T13:00:00Z"),
            "mistakes" : 0
        }
    ]

这个不会被退回的地方

Report
"submissions" : [
        {

            "date_submitted" : ISODate("2014-01-28T13:00:00Z"),
            "mistakes" : 0
        },
        {
            "date_submitted" : ISODate("2014-03-08T13:00:00Z"),
            "mistakes" : 11
        }
    ]

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid aggregation-framework


    【解决方案1】:

    这是因为您不是过滤嵌入数组的元素,而是过滤包含该元素的文档。

    这里可能有一个$elemMatch 子句,它允许您在单个元素上组合条件。但是 find 没有任何操作来获取 ma​​x 值。不要将这与$max 查询修饰符混淆,后者实际上剪辑正在使用的索引,不会超出这些范围进行搜索。

    所以这里你使用aggregate:

    db.collection.aggregate([
       // Optionally query to match and filter your documents.       
       //{ "$match: { /* Same conditions as find */ } },
    
       // Unwind the array
       { "$unwind": "$submissions" },
    
       // Filter all but 0 mistakes
       { "$match": { "submissions.mistakes": 0 } },
    
       // Group the results, taking the max entry and presuming by document `_id`
       { "$group": {
           "_id": "$_id",
           "date_submitted": { "$max": "$submissions.date_submitted" }
       }}
    
    ])
    

    这是过滤数组元素的一般过程。您可能会查看聚合的驱动程序实现,但表单始终是表示为此表单中的文档数组(散列)的管道。可能使用 moped 表单来获取收集方法。所以像:

    Report.collection.aggregate([ /* stages */ ])
    

    有关返回原始文档表格的更多信息,如果这是您的要求,请参阅here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2011-10-03
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多