How to get mongo command results in to a flat file

你说的曾经没有我的故事 提交于 2019-12-02 15:45:44

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

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.

Use this

mongo db_name --username user --password password < query1.js >> result.txt

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

DarwinFernandez
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

try this - return 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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!