聚合管道
Mongoid公开MongoDB的聚合管道,用于构建操作流程,以处理和返回结果。聚合管道是已弃用的map/reduce框架功能的超集。
基本用法
跨多个集合查询
聚合管道可以用于同时涉及多个引用关联的查询
class Band include Mongoid::Document has_many :tours has_many :awards field :name, type: String end class Tour include Mongoid::Document belongs_to :band field :year, type: Integer end class Award include Mongoid::Document belongs_to :band field :name, type: String end
要检索自2000年以来巡回演出并且至少有一个奖项的乐队,可以执行以下操作
band_ids = Band.collection.aggregate([ { '$lookup' => { from: 'tours', localField: '_id', foreignField: 'band_id', as: 'tours', } }, { '$lookup' => { from: 'awards', localField: '_id', foreignField: 'band_id', as: 'awards', } }, { '$match' => { 'tours.year' => {'$gte' => 2000}, 'awards._id' => {'$exists' => true}, } }, {'$project' => {_id: 1}}, ]) bands = Band.find(band_ids.to_a)
请注意,由于聚合管道是由MongoDB的Ruby驱动程序而不是Mongoid实现的,它返回原始BSON::Document
对象,而不是Mongoid::Document
模型实例。上面的例子只投影了_id
字段,然后用于加载完整模型。另一种选择是不执行此类投影,而与原始字段一起工作,这将消除在第二次查询(可能很大)中发送文档ID列表给Mongoid的需求。
构建器DSL
Mongoid提供了有限的支持,使用高级DSL构建聚合管道本身。以下聚合管道运算符受到支持
要构建一个管道,请在Criteria
实例上调用相应的聚合管道方法。聚合管道操作添加到Criteria
实例的pipeline
属性中。要执行管道,将pipeline
属性值传递给Collection#aggregate
方法。
例如,给定以下模型
class Tour include Mongoid::Document embeds_many :participants field :name, type: String field :states, type: Array end class Participant include Mongoid::Document embedded_in :tour field :name, type: String end
我们可以找出参与者访问过哪些州
criteria = Tour.where('participants.name' => 'Serenity',). unwind(:states). group(_id: 'states', :states.add_to_set => '$states'). project(_id: 0, states: 1) pp criteria.pipeline # => [{"$match"=>{"participants.name"=>"Serenity"}}, # {"$unwind"=>"$states"}, # {"$group"=>{"_id"=>"states", "states"=>{"$addToSet"=>"$states"}}}, # {"$project"=>{"_id"=>0, "states"=>1}}] Tour.collection.aggregate(criteria.pipeline).to_a
group
group
方法添加一个$group 聚合管道阶段。
字段表达式支持Mongoid符号运算符语法
criteria = Tour.all.group(_id: 'states', :states.add_to_set => '$states') criteria.pipeline # => [{"$group"=>{"_id"=>"states", "states"=>{"$addToSet"=>"$states"}}}]
或者,可以使用标准的MongoDB聚合管道语法
criteria = Tour.all.group(_id: 'states', states: {'$addToSet' => '$states'})
project
project
方法添加一个$project 聚合管道阶段。
参数应该是一个指定投影的哈希表
criteria = Tour.all.project(_id: 0, states: 1) criteria.pipeline # => [{"$project"=>{"_id"=>0, "states"=>1}}]
unwind
unwind
方法添加一个$unwind 聚合管道阶段。
参数可以是一个字段名,可以指定为符号或字符串,或者是一个哈希表或一个BSON::Document
实例
criteria = Tour.all.unwind(:states) criteria = Tour.all.unwind('states') criteria.pipeline # => [{"$unwind"=>"$states"}] criteria = Tour.all.unwind(path: '$states') criteria.pipeline # => [{"$unwind"=>{:path=>"$states"}}]