Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading and running an aggregation in mongo shell

Tags:

mongodb

I've coded an aggregation I want to run on a collection in the mongo shell. If I paste it directly into the shell, I have to do it line by line which is tedious and slow, especially when it doesn't work and I have to do it over. Therefore, I put it in a .js document and loaded it like this load("myaggregation.js") but that only returns true if the code is valid. How do I run the aggregation after loading it? I can't find any documentation about this. Do I have to use the nodejs driver?

like image 439
BrainLikeADullPencil Avatar asked Sep 15 '13 00:09

BrainLikeADullPencil


People also ask

How aggregation is performed in MongoDB?

In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.

What is aggregation in MongoDB explain with example?

An aggregation pipeline consists of one or more stages that process documents: Each stage performs an operation on the input documents. For example, a stage can filter documents, group documents, and calculate values. The documents that are output from a stage are passed to the next stage.

Which aggregation method is preferred for use by MongoDB?

The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. The aggregation pipeline can operate on a sharded collection.


2 Answers

Put your aggregation code in a function:

function my_aggregate() { 
    return db.foo.aggregate( [ ... ] );
}

and store that in your .js file.

Then run load to load it. You can also pass the filename on the commandline using the --shell commandline flag which will start the interactive shell after running any specified .js files.

Once the file is run your new function will be available to execute. Simply type

my_aggregate()

Update You do have to use an explicit return which I failed to mention. So in your case you would want 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"}}}]);
}
like image 77
friedo Avatar answered Sep 29 '22 20:09

friedo


Have you seen http://docs.mongodb.org/manual/tutorial/write-scripts-for-the-mongo-shell/?

Something like: mongo localhost:27017/test myjsfile.js

It also says that "You can execute a .js file from within the mongo shell, using the load() function".

like image 35
pfrank Avatar answered Sep 29 '22 18:09

pfrank