How to get mongo command results in to a flat file

后端 未结 8 2069
攒了一身酷
攒了一身酷 2021-01-30 06:26

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

相关标签:
8条回答
  • 2021-01-30 07:09

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

    0 讨论(0)
  • 2021-01-30 07:11

    Install MongoDB Compass, then it will have a tool to export query result to Json/CSV files.

    0 讨论(0)
  • 2021-01-30 07:17
    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
    
    0 讨论(0)
  • 2021-01-30 07:21

    Use this

    mongo db_name --username user --password password < query1.js >> result.txt
    
    0 讨论(0)
  • 2021-01-30 07:22

    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
    
    0 讨论(0)
  • 2021-01-30 07:25

    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.

    0 讨论(0)
提交回复
热议问题