Download and run aggregation in the mongo shell

I encoded the aggregation that I want to run in collections in the mongo shell. If I insert it directly into the shell, I have to do it on a line that is tedious and slow, especially when it does not work, and I have to do it. So I put it in a .js document and loaded it like this load("myaggregation.js") , but it only returns true if the code is valid. How to start aggregation after loading it? I can not find documentation about this. Should I use the nodejs driver?

+6
source share
4 answers

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"}}}]); } 
+7
source

I know this is a late answer, but I found a good way to handle this:

Create a js file containing the summary request:

 use blog; db.posts.aggregate([ ... my query ... ]); 

then you can just cat and transfer the file to the mongo client:

 cat myfile.js | mongo 
+2
source

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 the .js file from the mongo shell using the load () function."

+1
source

script.js file contents:

 aggrQuery = db.foo.aggregate([ {$group: {_id: '$bar', pop: {$max: '$buz'}}} ]) 

in mongo shell:

 > load('/file/location/script.js'); true >aggrQuery here will be output 
0
source

Source: https://habr.com/ru/post/953844/


All Articles