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?
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.
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.
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.
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"}}}]);
}
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With