Skip to content

Instantly share code, notes, and snippets.

@mpobrien
Created September 19, 2012 21:46
Show Gist options
  • Save mpobrien/3752507 to your computer and use it in GitHub Desktop.
Save mpobrien/3752507 to your computer and use it in GitHub Desktop.
mongo aggregation fluent API
//Usage
// example: unwind "tags" field, group by tag + count, save output to collection "FOO"
// db.things.agg().unwind("tags").group("tags", {total:{$sum:1}}).out("FOO").exec()
var AggHelper = function(collection){
this.collection = collection
this.db = collection.getDB()
this.pipeline = []
}
AggHelper.prototype.match = function(criteria){
if(!criteria){
throw "match needs a query object, like {'name' : 'bob'}"
}
this.pipeline.push({"$match" : criteria})
return this;
}
AggHelper.prototype.group = function(id, exprs){
if(!id){
throw "group needs an 'id' (grouping key) and a set of group operators, like {totalAge:{'$sum':'$age'}}"
}
groupexprs = exprs
groupexprs._id = "$" + id
this.pipeline.push({"$group" : groupexprs})
return this;
}
AggHelper.prototype.sort = function(info){
this.pipeline.push({"$sort" : info})
return this;
}
AggHelper.prototype.skip = function(n){
if(!n){
throw "skip needs an integer indicating the number of documents to skip."
}
this.pipeline.push({"$skip" : n})
return this;
}
AggHelper.prototype.limit = function(n){
if(!n){
throw "limit needs an integer indicating the max number of documents to limit."
}
this.pipeline.push({"$limit" : n})
return this;
}
AggHelper.prototype.unwind = function(fieldname){
if(!fieldname){
throw "unwind needs a string indicating the key of an array field to unwind"
}
this.pipeline.push({"$unwind" : "$" + fieldname})
return this;
}
AggHelper.prototype.toString = function(){
return tojson(this.pipeline)
}
AggHelper.prototype.project = function(fieldsinfo){
if(!fieldsinfo){
throw "project needs info about what to project"
}
this.pipeline.push({"$project" : fieldsinfo})
return this;
}
AggHelper.prototype.project = function(fieldsinfo){
if(!fieldsinfo){
throw "project needs info about what to project"
}
this.pipeline.push({"$project" : fieldsinfo})
return this;
}
AggHelper.prototype.out = function(out_collection_name){
if(!out_collection_name){
throw "out() needs a string for the name of the collection to save output to."
}
this.out_collection_name = out_collection_name
return this;
}
AggHelper.prototype.exec = function(){
var result = this.collection.aggregate(this.pipeline)
if(this.out_collection_name){
var output_collection = this.db.getCollection(this.out_collection_name)
for(var i=0;i<result.result.length;i++){
output_collection.insert(result.result[i])
}
}
return result;
}
DBCollection.prototype.agg = function(){
return new AggHelper(this)
}
@TylerBrock
Copy link

but how do I mongo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment