Put the aggregation code in the function:
function my_aggregate() { return db.foo.aggregate( [ ... ] ); }
and save this in your .js file.
Then run load to load it. You can also pass the file name on the command line using the --shell command line --shell , which will launch the interactive shell after running any specified .js files.
After starting the file, your new function will be available for execution. Just enter
my_aggregate()
Refresh . You need to use an explicit return , which I did not mention. So in your case you need something like:
function my_aggregate() { return db.zips.aggregate([{ $match: { state: { $in: [ "CA", "NY" ] } }},{ $group:{ _id : { "state" : "$state","city" : "$city" }, pop : { $sum: "$pop"}}},{ $match: { pop: { $gt: 25000 } }},{$group:{ _id : { "city" : "$city"}, pop : { $avg: "$pop"}}}]); }
source share