【问题标题】:Sorting by number of elements in array of the document in mongo [duplicate]按mongo中文档数组中的元素数排序[重复]
【发布时间】:2011-09-21 03:22:25
【问题描述】:

假设我有一个答案集合,其中每个答案都包含一个 user_ids 数组。

  • 回答 has_and_belongs_to_many:用户

是否可以进行按 user_id 数量排序的查询?

Answer.all.desc(num_user_ids)

我可以缓存这个号码,但我希望我不必这样做。我正在使用 mongoid

【问题讨论】:

    标签: mongodb mongoid


    【解决方案1】:

    这可能是这个问题的重复:How can I sort MongoDB query results by inner array size?

    总而言之:不,您不能按照自己的意愿按数组长度排序,建议在包含用户数量的文档中存储一个附加字段。

    不过,您可以使用 MapReduce 做到这一点。但这会产生另一个表,这可能是不希望的。

    【讨论】:

      【解决方案2】:

      这是一个老问题,但它是“mongoid 按数组长度排序”的最高结果,它不再正确。

      这个查询可以通过 in this question 的 Mongo 集合框架来完成。

      当在 mongoid 中完成时,它看起来像这样:

      unwind = { '$unwind' => '$tags' }
      group = { '$group' =>
          { '_id' => '$_id', 'tags' => { '$push' => '$tags' }, 'count' => { '$sum' => 1 } }
      }
      sort = { '$sort' => { 'count' => 1 } }
      Photo.collection.aggregate([unwind, group, sort])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2015-05-07
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多