Reputation: 4163
I need to export mongodb aggregation query result to file. I am connected to remote server so I need something like db.myCollection.aggregate([...]).printToFile('C:\Downloads\resultFile.txt')
Is it possible?
Upvotes: 2
Views: 1252
Reputation: 1912
Add quotes to your connection string and use printjson()
to print JSON objects. Note that the aggregate()
returns a cursor and thus you have to loop through them. If your don't use forEach
, it only returns top 20.
Here is a one line command.
mongo --quiet "mongodb://junior:SECRETPASSWORD@mongo4:9000,mongo5:9000/WebApp?authSource=admin&replicaSet=rs0&readPreference=secondaryPreferred" --eval 'db.cars.aggregate([...]).forEach(function(doc) { printjson(doc);})' > output.txt
In more readable multi-line format
mongo --quiet \
"mongodb://junior:SECRETPASSWORD@mongo4:9000,mongo5:9000/WebApp?authSource=admin&replicaSet=rs0&readPreference=secondaryPreferred" \
--eval 'db.cars.aggregate([...]).forEach(function(doc) \
{ printjson(doc);})' > output.txt
Upvotes: 6
Reputation: 49945
I assume that Windows is your operating system based on your sample path. In that case you can use >
to redirect console command output to a file. To run aggregate
directly from cmd you can use mongo
as a client with --eval parameter which allows you to run JavaScript code, try something like this:
C:\Program Files\MongoDB\Server\4.0\bin>mongo --host <yourhost> --port <yourport> --eval "db.myCollection.aggregate([...])" > C:\Downloads\resultFile.txt
Upvotes: 1