How to get mongo command results in to a flat file

2020-05-12 11:52发布

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.

7条回答
贼婆χ
2楼-- · 2020-05-12 12:33

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楼-- · 2020-05-12 12:33

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
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-05-12 12:34

mongoexport --db db_name --collection collection_name --csv --out file_name.csv -f field1,field2, field3

查看更多
冷血范
5楼-- · 2020-05-12 12:39

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+.

查看更多
太酷不给撩
6楼-- · 2020-05-12 12:40
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
查看更多
Explosion°爆炸
7楼-- · 2020-05-12 12:43

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

查看更多
登录 后发表回答