Skip to content

Instantly share code, notes, and snippets.

@ryw
Created February 5, 2014 16:14
Show Gist options
  • Save ryw/8827179 to your computer and use it in GitHub Desktop.
Save ryw/8827179 to your computer and use it in GitHub Desktop.
Meteor aggregation
Meteor.publishAggregation = (params) ->
initializing = true
dummy = Random.id()
pub = params.handle
collection = params.collection
handle = collection.find(params.filter, params.options).observeChanges
added: (id, fields) ->
if !initializing
pub.changed(params.name, dummy, collection.aggregate(params.pipeline)[0])
removed: (id) ->
pub.changed(params.name, dummy, collection.aggregate(params.pipeline)[0])
initializing = false
pub.added(params.name, dummy, collection.aggregate(params.pipeline)[0])
pub.ready()
pub.onStop -> handle.stop()
Meteor.publish 'avgMeetingsCreated', ->
sum =
$group:
_id: '$userId'
sum:
'$sum': 1
avg =
$group:
_id: null
avg:
'$avg': '$sum'
Meteor.publishAggregation
handle: this
name: 'avgMeetingsCreated'
collection: Meetings
pipeline: [sum, avg]
filter: {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment