How to get mongo command results in to a flat file - mongodb

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.

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

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

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

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

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

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

Related

In mongodb can we download multiple collections with one command

Now I am using mongoexport command to download a collection and mongodump to download whole db data. Is it possible to download multiple collections with one command?
The command I use to download single collection is as below:
mongoexport -h $MONGODB_SERVICE_HOST -d countly -c collection_name -u $MONGODB_USER -p $MONGODB_PASSWORD -o /opt/app-root/src/filename
Try using automating the task by writing bash script like below:-
replace values accordingly.
db=<db>
collection_list="<collection1> <collection2> <collection3>"
host=127.0.0.1
port=<port>
out_prefix=/Temp
for collection in $collection_list; do
echo $collection
out_dir="${out_prefix}/${db}_${collection}/"
mkdir -p ${out_dir}
mongodump --host $host --port $port --collection $collection --db $db --out ${out_dir}
done

MongoDB find() output to file

Is there a way to write the output of a MongoDB find() query to a file just by simply using a Linux shell command or running a script?
Right now I have to manually type in step-by-step. Example:
$ mongo
> use owndb
> db.CollectionName.find(<query>) ### and then copy and paste the result on a text editor
You may try this:
mongo --quiet dbname --eval 'printjson(db.collection.find().toArray())' > output.json
You can use mongoexport for that.
Example:
mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json

export a csv from mongodb

I have two collections in my mongodb namely
1.companies
2.contacts
Both the companies and contact collection are interlinked. I want to export a particular companies contact into a csv. I have tried a mongo export command as follows
mongoexport --csv -d dbname -c contacts
-q {"employment_details.company_id":ObjectId("50926cff9fe3125819006dc7")};
-f {"first_name","last_name","title"} -o export.csv
I get a error as follows
SyntaxError: missing ; before statement (shell):1.
Please help me. Thanks in Advance
There could be a couple of things going on here. First, are you running mongoexport from the command line or from the mongo shell? The mongoexport command is run from the command line.
Secondly, you need to properly format the query and field parameters. You could enclose the query with single quotes, and the filed name is not a JSON document, but just a list of fields.
This would look like the following from the command line:
mongoexport --csv -d dbname -c contacts -q '{"employment_details.company_id":ObjectId("50926cff9fe3125819006dc7")}' -f "first_name","last_name","title" -o export.csv
The following query will work if it is running from commandLine
mongoexport -h host -d dbname -c contacts --csv -q '{"employment_details.company_id":ObjectId("50926cff9fe3125819006dc7")}' -f first_name,last_name,title -o export.csv

How to export all collections in MongoDB?

I want to export all collections in MongoDB by the command:
mongoexport -d dbname -o Mongo.json
The result is:
No collection specified!
The manual says, if you don't specify a collection, all collections will be exported.
However, why doesn't this work?
http://docs.mongodb.org/manual/reference/mongoexport/#cmdoption-mongoexport--collection
My MongoDB version is 2.0.6.
For lazy people, use mongodump, it's faster:
mongodump -d <database_name> -o <directory_backup>
And to "restore/import" it (from directory_backup/dump/):
mongorestore -d <database_name> <directory_backup>
This way, you don't need to deal with all collections individually. Just specify the database.
Note that I would recommend against using mongodump/mongorestore for big data storages. It is very slow and once you get past 10/20GB of data it can take hours to restore.
I wrote bash script for that. Just run it with 2 parameters (database name, dir to store files).
#!/bin/bash
if [ ! $1 ]; then
echo " Example of use: $0 database_name [dir_to_store]"
exit 1
fi
db=$1
out_dir=$2
if [ ! $out_dir ]; then
out_dir="./"
else
mkdir -p $out_dir
fi
tmp_file="fadlfhsdofheinwvw.js"
echo "print('_ ' + db.getCollectionNames())" > $tmp_file
cols=`mongo $db $tmp_file | grep '_' | awk '{print $2}' | tr ',' ' '`
for c in $cols
do
mongoexport -d $db -c $c -o "$out_dir/exp_${db}_${c}.json"
done
rm $tmp_file
For local and remote dump and restore:
For Local
Local dump
mongodump -d mydb -o ./mongo-backup
Local restore
mongorestore -d mydb ./mongo-backup/mydb
For remote
Remote dump
mongodump --uri "mongodb+srv://Admin:MYPASS#appcluster.15lf4.mongodb.net/mytestdb" -o ./mongo-backup
Remote restore
mongorestore --uri "mongodb+srv://Admin:MYPASS#appcluster.15lf4.mongodb.net/mytestdb" ./mongo-backup/mytestdb
Update:
If you're using mongo 4.0 you may encounter a snapshot error, Then you can run with this argument: --forceTableScan. See here for more information. The error is something like this:
mongodump error reading collection: BSON field 'FindCommandRequest.snapshot' is an unknown field.
To export all collections:
mongodump -d database_name -o directory_to_store_dumps
To restore them:
mongorestore -d database_name directory_backup_where_mongodb_tobe_restored
Follow the steps below to create a mongodump from the server and import it another server/local machine which has a username and a password
1. mongodump -d dbname -o dumpname -u username -p password
2. scp -r user#remote:~/location/of/dumpname ./
3. mongorestore -d dbname dumpname/dbname/ -u username -p password
Please let us know where you have installed your Mongo DB? (either in Ubuntu or in Windows)
For Windows:
Before exporting you must connect to your Mongo DB in cmd prompt and make sure that you are able to connect to your local host.
Now open a new cmd prompt and execute the below command,
mongodump --db database name --out path to save
eg: mongodump --db mydb --out c:\TEMP\op.json
Visit https://www.youtube.com/watch?v=hOCp3Jv6yKo for more details.
For Ubuntu:
Login to your terminal where Mongo DB is installed and make sure you are able to connect to your Mongo DB.
Now open a new terminal and execute the below command,
mongodump -d database name -o file name to save
eg: mongodump -d mydb -o output.json
Visit https://www.youtube.com/watch?v=5Fwd2ZB86gg for more details.
Previous answers explained it well, I am adding my answer to help in case you are dealing with a remote password protected database
mongodump --host xx.xxx.xx.xx --port 27017 --db your_db_name --username your_user_name --password your_password --out /target/folder/path
I realize that this is quite an old question and that mongodump/mongorestore is clearly the right way if you want a 100% faithful result, including indexes.
However, I needed a quick and dirty solution that would likely be forwards and backwards compatible between old and new versions of MongoDB, provided there's nothing especially wacky going on. And for that I wanted the answer to the original question.
There are other acceptable solutions above, but this Unix pipeline is relatively short and sweet:
mongo --quiet mydatabase --eval "db.getCollectionNames().join('\n')" | \
grep -v system.indexes | \
xargs -L 1 -I {} mongoexport -d mydatabase -c {} --out {}.json
This produces an appropriately named .json file for each collection.
Note that the database name ("mydatabase") appears twice. I'm assuming the database is local and you don't need to pass credentials but it's easy to do that with both mongo and mongoexport.
Note that I'm using grep -v to discard system.indexes, because I don't want an older version of MongoDB to try to interpret a system collection from a newer one. Instead I'm allowing my application to make its usual ensureIndex calls to recreate the indexes.
You can do it using the mongodump command
Step 1 : Open command prompt
Step 2 : go to bin folder of your mongoDB installation (C:\Program Files\MongoDB\Server\4.0\bin)
Step 3 : then execute the following command
mongodump -d your_db_name -o destination_path
your_db_name = test
destination_path = C:\Users\HP\Desktop
Exported files will be created in destination_path\your_db_name folder (in this example C:\Users\HP\Desktop\test)
References : o7planning
In case you want to connect a remote mongoDB server like mongolab.com, you should pass connection credentials
eg.
mongoexport -h id.mongolab.com:60599 -u username -p password -d mydb -c mycollection -o mybackup.json
If you are OK with the bson format, then you can use the mongodump utility with the same -d flag. It will dump all the collections to the dump directory (the default, can be changed via the -o option) in the bson format. You can then import these files using the mongorestore utility.
If you're dealing with remote databases you can try these commands given that you don't mind the output being BSON
1. Dump out as a gzip archive
mongodump --uri="mongodb://YOUR_USER_ID:YOUR_PASSWORD#YOUR_HOST_IP/YOUR_DB_NAME" --gzip --archive > YOUR_FILE_NAME
2. Restore (Copy a database from one to another)
mongorestore --uri="mongodb://$targetUser:$targetPwd#$targetHost/$targetDb" --nsFrom="$sourceDb.*" --nsTo="$targetDb.*" --gzip --archive
You can use mongo --eval 'printjson(db.getCollectionNames())' to get the list of collections
and then do a mongoexport on all of them.
Here is an example in ruby
out = `mongo #{DB_HOST}/#{DB_NAME} --eval "printjson(db.getCollectionNames())"`
collections = out.scan(/\".+\"/).map { |s| s.gsub('"', '') }
collections.each do |collection|
system "mongoexport --db #{DB_NAME} --collection #{collection} --host '#{DB_HOST}' --out #{collection}_dump"
end
I needed the Windows batch script version. This thread was useful, so I thought I'd contribute my answer to it too.
mongo "{YOUR SERVER}/{YOUR DATABASE}" --eval "rs.slaveOk();db.getCollectionNames()" --quiet>__collections.txt
for /f %%a in ('type __collections.txt') do #set COLLECTIONS=%%a
for %%a in (%COLLECTIONS%) do mongoexport --host {YOUR SERVER} --db {YOUR DATABASE} --collection %%a --out data\%%a.json
del __collections.txt
I had some issues using set /p COLLECTIONS=<__collections.txt, hence the convoluted for /f method.
I found after trying lots of convoluted examples that very simple approach worked for me.
I just wanted to take a dump of a db from local and import it on a remote instance:
on the local machine:
mongodump -d databasename
then I scp'd my dump to my server machine:
scp -r dump user#xx.xxx.xxx.xxx:~
then from the parent dir of the dump simply:
mongorestore
and that imported the database.
assuming mongodb service is running of course.
If you want, you can export all collections to csv without specifying --fields (will export all fields).
From http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/ run this bash script
OIFS=$IFS;
IFS=",";
# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT
# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);
# for each collection
for ((i=0; i<${#collectionArray[#]}; ++i));
do
echo 'exporting collection' ${collectionArray[$i]}
# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done
IFS=$OIFS;
If you want to dump all collections in all databases (which is an expansive interpretation of the original questioner's intent) then use
mongodump
All the databases and collections will be created in a directory called 'dump' in the 'current' location
you can create zip file by using following command .It will create zip file of database {dbname} provided.You can later import the following zip file in you mongo DB.
Window filepath=C:\Users\Username\mongo
mongodump --archive={filepath}\+{filename}.gz --gzip --db {dbname}
Here's what worked for me when restoring an exported database:
mongorestore -d 0 ./0 --drop
where ./contained the exported bson files. Note that the --drop will overwrite existing data.
if you want to use mongoexport and mongoimport to export/import each collection from database, I think this utility can be helpful for you.
I've used similar utility couple of times;
LOADING=false
usage()
{
cat << EOF
usage: $0 [options] dbname
OPTIONS:
-h Show this help.
-l Load instead of export
-u Mongo username
-p Mongo password
-H Mongo host string (ex. localhost:27017)
EOF
}
while getopts "hlu:p:H:" opt; do
MAXOPTIND=$OPTIND
case $opt in
h)
usage
exit
;;
l)
LOADING=true
;;
u)
USERNAME="$OPTARG"
;;
p)
PASSWORD="$OPTARG"
;;
H)
HOST="$OPTARG"
;;
\?)
echo "Invalid option $opt"
exit 1
;;
esac
done
shift $(($MAXOPTIND-1))
if [ -z "$1" ]; then
echo "Usage: export-mongo [opts] <dbname>"
exit 1
fi
DB="$1"
if [ -z "$HOST" ]; then
CONN="localhost:27017/$DB"
else
CONN="$HOST/$DB"
fi
ARGS=""
if [ -n "$USERNAME" ]; then
ARGS="-u $USERNAME"
fi
if [ -n "$PASSWORD" ]; then
ARGS="$ARGS -p $PASSWORD"
fi
echo "*************************** Mongo Export ************************"
echo "**** Host: $HOST"
echo "**** Database: $DB"
echo "**** Username: $USERNAME"
echo "**** Password: $PASSWORD"
echo "**** Loading: $LOADING"
echo "*****************************************************************"
if $LOADING ; then
echo "Loading into $CONN"
tar -xzf $DB.tar.gz
pushd $DB >/dev/null
for path in *.json; do
collection=${path%.json}
echo "Loading into $DB/$collection from $path"
mongoimport $ARGS -d $DB -c $collection $path
done
popd >/dev/null
rm -rf $DB
else
DATABASE_COLLECTIONS=$(mongo $CONN $ARGS --quiet --eval 'db.getCollectionNames()' | sed 's/,/ /g')
mkdir /tmp/$DB
pushd /tmp/$DB 2>/dev/null
for collection in $DATABASE_COLLECTIONS; do
mongoexport --host $HOST -u $USERNAME -p $PASSWORD -db $DB -c $collection --jsonArray -o $collection.json >/dev/null
done
pushd /tmp 2>/dev/null
tar -czf "$DB.tar.gz" $DB 2>/dev/null
popd 2>/dev/null
popd 2>/dev/null
mv /tmp/$DB.tar.gz ./ 2>/dev/null
rm -rf /tmp/$DB 2>/dev/null
fi
If you have this issue:
Failed: can't create session: could not connect to server: connection() : auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
then add --authenticationDatabase admin
eg:
mongodump -h 192.168.20.30:27018 --authenticationDatabase admin -u dbAdmin -p dbPassword -d dbName -o path/to/folder
If you want to backup all the dbs on the server, without having the worry about that the dbs are called, use the following shell script:
#!/bin/sh
md=`which mongodump`
pidof=`which pidof`
mdi=`$pidof mongod`
dir='/var/backup/mongo'
if [ ! -z "$mdi" ]
then
if [ ! -d "$dir" ]
then
mkdir -p $dir
fi
$md --out $dir >/dev/null 2>&1
fi
This uses the mongodump utility, which will backup all DBs if none is specified.
You can put this in your cronjob, and it will only run if the mongod process is running. It will also create the backup directory if none exists.
Each DB backup is written to an individual directory, so you can restore individual DBs from the global dump.
I dump all collection on robo3t.
I run the command below on vagrant/homestead. It's work for me
mongodump --host localhost --port 27017 --db db_name --out db_path
Some of the options are now deprecated, in version 4.4.5 here is how I have done it
mongodump --archive="my-local-db" --db=my
mongorestore --archive="my-local-db" --nsFrom='my.*' --nsTo='mynew.*'
Read more about restore here: https://docs.mongodb.com/database-tools/mongorestore/
First, of Start the Mongo DB - for that go to the path as ->
C:\Program Files\MongoDB\Server\3.2\bin and click on the mongod.exe file to start MongoDB server.
Command in Windows to Export
Command to export MongoDB database in Windows from "remote-server" to the local machine in directory C:/Users/Desktop/temp-folder from the remote server with the internal IP address and port.
C:\> mongodump --host remote_ip_address:27017 --db <db-name> -o C:/Users/Desktop/temp-folder
Command in Windows to Import
Command to import MongoDB database in Windows to "remote-server" from local machine directory C:/Users/Desktop/temp-folder/db-dir
C:\> mongorestore --host=ip --port=27017 -d <db-name> C:/Users/Desktop/temp-folder/db-dir
This is the simplest technique to achieve your aim.
mongodump -d db_name -o path/filename.json
#mongodump using sh script
#!/bin/bash
TIMESTAMP=`date +%F-%H%M`
APP_NAME="folder_name"
BACKUPS_DIR="/xxxx/tst_file_bcup/$APP_NAME"
BACKUP_NAME="$APP_NAME-$TIMESTAMP"
/usr/bin/mongodump -h 127.0.0.1 -d <dbname> -o $BACKUPS_DIR/$APP_NAME/$BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUPS_DIR/$APP_NAME/$BACKUP_NAME
rm -rf /home/wowza_analytics_bcup/wowza_analytics/wowza_analytics
### 7 days old backup delete automaticaly using given command
find /home/wowza_analytics_bcup/wowza_analytics/ -mindepth 1 -mtime +7 -delete
There are multiple options depending on what you want to do
1) If you want to export your database to another mongo database, you should use mongodump. This creates a folder of BSON files which have metadata that JSON wouldn't have.
mongodump
mongorestore --host mongodb1.example.net --port 37017 dump/
2) If you want to export your database into JSON you can use mongoexport except you have to do it one collection at a time (this is by design). However I think it's easiest to export the entire database with mongodump and then convert to JSON.
# -d is a valid option for both mongorestore and mongodump
mongodump -d <DATABASE_NAME>
for file in dump/*/*.bson; do bsondump $file > $file.json; done
Even in mongo version 4 there is no way to export all collections at once. Export the specified collection to the specified output file from a local MongoDB instance running on port 27017 you can do with the following command:
.\mongoexport.exe --db=xstaging --collection=products --out=c:/xstaging.products.json
Open the Connection
Start the server
open new Command prompt
Export:
mongo/bin> mongoexport -d webmitta -c domain -o domain-k.json
Import:
mongoimport -d dbname -c newCollecionname --file domain-k.json
Where
webmitta(db name)
domain(Collection Name)
domain-k.json(output file name)

How to export collection to CSV in MongoDB?

How do you export all the records in a MongoDB collection to a .csv file?
mongoexport --host localhost --db dbname --collection name --type=csv > test.csv
This asks me to specify name of the fields I need to export. Can I just export all the fields without specifying the names of fields?
#karoly-horvath has it right. Fields are required for csv.
According to this bug in the MongoDB issue tracker https://jira.mongodb.org/browse/SERVER-4224 you MUST provide the fields when exporting to a csv. The docs are not clear on it. That is the reason for the error.
Try this:
mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName
UPDATE:
This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes
Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"`
to
Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "`
VERSION 3.0 AND ABOVE:
You should use --type=csv instead of --csv since it has been deprecated.
More details: https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format
Full command:
mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName
Also, you are not allowed spaces between comma separated field names.
BAD:
-f firstname, lastname
GOOD:
-f firstname,lastname
mongoexport --help
....
-f [ --fields ] arg comma separated list of field names e.g. -f name,age
--fieldFile arg file with fields names - 1 per line
You have to manually specify it and if you think about it, it makes perfect sense. MongoDB is schemaless; CSV, on the other hand, has a fixed layout for columns. Without knowing what fields are used in different documents it's impossible to output the CSV dump.
If you have a fixed schema perhaps you could retrieve one document, harvest the field names from it with a script and pass it to mongoexport.
If you want, you can export all collections to csv without specifying --fields (will export all fields).
From http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/ run this bash script
OIFS=$IFS;
IFS=",";
# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT
# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);
# for each collection
for ((i=0; i<${#collectionArray[#]}; ++i));
do
echo 'exporting collection' ${collectionArray[$i]}
# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done
IFS=$OIFS;
works for me remoting to a docker container with mongo:4.2.6
mongoexport -h mongodb:27017 --authenticationDatabase=admin -u username -p password -d database -c collection -q {"created_date": { "$gte": { "$date": "2020-08-03T00:00:00.000Z" }, "$lt": { "$date": "2020-08-09T23:59:59.999Z" } } } --fields=somefield1,somefield2 --type=csv --out=/archive.csv
Easy export csv or json file With Mongo Compass tool
Mongo Compass As the GUI for MongoDB, MongoDB Compass allows you to make smarter decisions about document structure, querying, indexing, document validation, and more. Commercial subscriptions include technical support for MongoDB Compass.
https://www.mongodb.com/try/download/compass
I could not get mongoexport to do this for me. I found that,to get an exhaustive list of all the fields, you need to loop through the entire collection once. Use this to generate the headers. Then loop through the collection again to populate these headers for each document.
I've written a script to do just this. Converting MongoDB docs to csv irrespective of schema differences between individual documents.
https://github.com/surya-shodan/mongoexportcsv
Also if you want to export inner json fields use dot (. operator).
JSON record:
{
"_id" : "00118685076F2C77",
"value" : {
"userIds" : [
"u1"
],
"deviceId" : "dev"
}
mongoexport command with dot operator (using mongo version 3.4.7):
./mongoexport --host localhost --db myDB --collection myColl
--type=csv --out out.csv --fields value.deviceId,value.userIds
Output csv:
value.deviceId,value.userIds
d1,"[""u1""]"
d2,"[""u2""]"
Note: Make sure you do not export an array. It would corrupt the CSV format like field userIds shown above
Solution for MongoDB Atlas users!
Add the --fields parameter as comma separated field names enclosed in double inverted quotes:
--fields "<FIELD 1>,<FIELD 2>..."
This is complete example:
mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."
This working for me Try it
mongoexport --host cluster0-shard-dummy-link.mongodb.net:27017 --db yourdbname --forceTableScan --collection users --type json --out /var/www/html/user.json --authenticationDatabase admin --ssl --username Yourusername --password Yourpassword
Above cmd return whole data of the users collection
if you want filter field then add --fields=email,name
For all those who are stuck with an error.
Let me give you guys a solution with a brief explanation of the same:-
command to connect:-
mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin
--host --> host of Mongo server
--port --> port of Mongo server
-u --> username
-p --> password
--db --> db from which you want to export
--collection --> collection you want to export
--type --> type of export in my case CSV
--out --> file name where you want to export
--fields --> all the fields you want to export (don't give spaces in between two field name in between commas in case of CSV)
--authenticationDatabase --> database where all your user information is stored
Below command used to export collection to CSV format.
Note: naag is database, employee1_json is a collection.
mongoexport --db naag--collection employee1_json --type csv --out /home/orienit/work/mongodb/employee1_csv_op1