Skip to content

Instantly share code, notes, and snippets.

@justinko
Created June 10, 2013 18:00
Show Gist options
  • Save justinko/5750883 to your computer and use it in GitHub Desktop.
Save justinko/5750883 to your computer and use it in GitHub Desktop.
Demonstrate MongoDB aggregation with the Ruby Mongoid gem.
require 'mongoid'
require 'pp'
Mongoid.configure do |config|
config.allow_dynamic_fields = false
config.connect_to 'mongo_test', { consistency: :strong }
end
Mongoid.default_session.drop
class Event
include Mongoid::Document
include Mongoid::Timestamps
has_many :activities, as: :subject
end
class Activity
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :subject, polymorphic: true
field :name, type: String
field :action, type: Symbol
end
event = Event.create!
event2 = Event.create!
event3 = Event.create!
Activity.create! subject: event, created_at: 2.seconds.ago, name: 'a', action: :tab
Activity.create! subject: event, created_at: 1.second.ago, name: 'b', action: :share
Activity.create! subject: event, name: 'c', action: :follow
Activity.create! subject: event2, name: 'd', action: :share
Activity.create! subject: event2, name: 'e', action: :follow, created_at: 5.seconds.ago
Activity.create! subject: event2, name: 'f', action: :comment
Activity.create! subject: event3, name: 'g', action: :share
puts Activity.count
puts Activity.all.to_a.inspect
puts
pp Activity.collection.aggregate([
{
'$sort' => {'created_at' => 1}
},
{
'$match' => {
'action' => {
'$nin' => [:comment, :favorite]
}
}
},
{
'$project' => {
'subject' => {
'subject_id' => '$subject_id',
'subject_type' => '$subject_type'
},
'name' => 1,
'id' => '$_id'
}
},
{
'$group' => {
'_id' => '$subject',
'name' => {'$first' => '$name'},
'others_count' => {'$sum' => 1},
'id' => {'$first' => '$id'}
}
},
{
'$project' => {
'_id' => '$id',
'name' => 1,
'others_count' => {'$subtract' => ['$others_count', 1]}
}
}
])
# [{"_id"=>"51b61350cfe415b9b400000a", "name"=>"g", "others_count"=>0},
# {"_id"=>"51b61350cfe415b9b4000004", "name"=>"a", "others_count"=>2},
# {"_id"=>"51b61350cfe415b9b4000008", "name"=>"e", "others_count"=>1}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment