Mongoid $project 聚合没有 return 任何东西

Mongoid $project aggregation doesn't return anything

我正在尝试使用 Mongoid 执行以下聚合:

 Award.collection.aggregate( [ {"$project" => {:"value.amount"=> 1}} ] )

这个returns:

#<Mongo::Collection::View::Aggregation:0x0055cc6e8658b8
@options={},
@pipeline=[{"$project"=>{:"value.amount"=>1}}],
@view=#<Mongo::Collection::View:0x47168257993960   
namespace='elvis_development.awards @selector={} @options={}>>

所以没有结果但也没有错误。这个版本的语法与他们在 the docs 中给出的示例相同,但我也尝试了不同的语法,但没有成功。在 mongo shell 这个:

db.awards.aggregate( [ { $project : { value.amount : 1 } } ] )

returns想要的结果。 我使用 MongoDB v3.0.7 和 Mongoid 5.0.1,这是我的模型:

class Award
  include Mongoid::Document
  include Mongoid::Elasticsearch

  # Associations
  belongs_to :document
  embeds_one :date, class_name: "AwardDate", inverse_of: :award
  embeds_one :value, class_name: "Value", inverse_of: :award

 accepts_nested_attributes_for :value, :date

  # Fields
 field :title, type: String
 field :description, type: String

 elasticsearch!({
  prefix_name: false,
  index_name: 'awards',
  wrapper: :load
 })
end 

我是不是做错了什么?我在 this example on mongo_ruby_driver Github 中注意到支持 $project 聚合,但我尝试使用嵌套属性和非嵌套属性得到相同的结果。我意识到我可以通过正常检索来做到这一点,但我更喜欢聚合,因为它们更快,而且我有一个大数据集。任何想法将不胜感激。

现代版本的 Mongoid(v5 和更高版本)现在使用现代 mongodb ruby driver 而不是旧的 "moped" Mongoid v3 和 v4 驱动程序。

这意味着 .aggregate() returns a "cursor", or specifically a Mongo::Collection::View::Readable 对象而不是普通的对象数组,这与其他现代驱动程序版本一致。

因此,通过标准方式迭代 "cursor"。即:

require "pp"

Award.collection.aggregate( [ {"$project" => { "value.amount"=> 1}} ] ).each do | doc |
    pp doc
end

这将为响应中的每个文档提供如下输出:

{"_id"=>BSON::ObjectId('564c4836023fb886145f8063'), "value"=>{"amount"=>1.0}}

如您所愿。