问题
How do I export the results of a MongoDB command to a flat file
For example, If I am to get db.collectionname.find()
into a flat file.
I tried db.collectionname.find() >> "test.txt"
doesnt seem to work.
回答1:
you can try the following from the command line
mongo 127.0.0.1/db --eval "var c = db.collection.find(); while(c.hasNext()) {printjson(c.next())}" >> test.txt
assuming you have a database called 'db' running on localhost and a collection called 'collection' this will export all records into a file called test.txt
If you have a longer script that you want to execute you can also create a script.js file and just use
mongo 127.0.0.1/db script.js >> test.txt
I hope this helps
回答2:
I know of no way to do that from the mongo shell directly, but you can get mongoexport to execute queries and send the results to a file with the -q and -o options:
mongoexport -h mongo.dev.priv -d models -c profiles -q '{ $query : { _id : "MRD461000" } }' -o MRD_Series1.json
The above hits queries the profiles collection in the models database grabbing the JSON document for _id = "MRD641000". Works for me.
回答3:
Use this
mongo db_name --username user --password password < query1.js >> result.txt
回答4:
Having missed the db needing to be the actual db in Peshkira's answer, here is a general syntax for a one liner in shell (assuming no password):
mongo <host>:<db name> --eval "var x = <db name>.<collection name>.<query>; while(x.hasNext()) { printjson( x.next() ) }" >> out.txt
I tested it both on my mac and Google cloud Ubuntu 15 with Mongo 3+.
回答5:
Try this - returns a json file with the data of the query, you can change .json
for .txt
and other.
mongoexport --db products --collection clicks --query '{"createdInt":{$gte:20190101}, "clientId":"123", "country":"ES"}' --out clicks-2019.json
回答6:
mongoexport --host 127.0.0.1 --port 27017 --username youruser -p yourpass \
-d yourDatabaseName -c collectionName --type csv \
--fields field1,field2 -q '{"field1" : 1495730914381}' \
--out report.csv
回答7:
mongoexport --db db_name --collection collection_name --csv --out file_name.csv -f field1,field2, field3
来源:https://stackoverflow.com/questions/12823990/how-to-get-mongo-command-results-in-to-a-flat-file