How to export all collections in MongoDB?
Asked Answered
L

34

467

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.

Ludwigg answered 29/6, 2012 at 3:21 Comment(5)
What version of MongoDB are you using? The wiki documentation for mongoexport suggests this is a command line tool for exporting a collection. Perhaps the ability to export multiple collections is for a newer version? If you want to backup all collections in a database, mongodump will export all collections to BSON.Stalkinghorse
It looks like the option to use mongoexport for all collections is a planned featured that hasn't been scheduled yet: SERVER-201 .. so mongodump is currently your best option for exporting a complete database. It wouldn't be too difficult to write the equivalent of mongoexport using one of the MongoDB client drivers.Stalkinghorse
You should mark an answer as accepted. My vote is for https://mcmap.net/q/80084/-how-to-export-all-collections-in-mongodbOssicle
For the record, MongoDB documentation states Avoid using mongoimport and mongoexport for full instance production backups. They do not reliably preserve all rich BSON data types, because JSON can only represent a subset of the types supported by BSON. Use mongodump and mongorestore as described in MongoDB Backup Methods for this kind of functionality. So it's not just for lazy people as Mentor Reka states but is also the preferred method of doing this.Ezaria
In the mongo document, it stats as a collection should be specified You must specify the collection to export.I referred the same documentPhlegm
D
897

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.

Disbelief answered 17/5, 2013 at 9:31 Comment(18)
Isn't there a compatibility problem between JSON and BSON ?Wellchosen
The data format used by mongodump from version 2.2 or later is incompatible with earlier versions of mongod. Do not use recent versions of mongodump to back up older data stores.Gatecrasher
I believed the restore command is "mongorestore -b DATABASE ./dump-folder" (where ./dump-folder is the path or your exported data).Mientao
"mongorestore -d DATABASE ./dump-folder"Lance
Great, but how could I exclude a collection (sessions)?Centum
I just keep getting SyntaxError: Unexpected identifier when trying to run mongodump. Any ideas?Cletacleti
@LucaSteeb use --excludeCollection=sessionsAchondroplasia
I tried this and get error: don't know what to do with file "0/objects.bson", skipping...Samford
I tried mongodump but I get an security error on system.profile collection :(Udella
Works but if you export with mongoDB 3.2 and import 3.4 and you have an error about the indexes do the import with --noIndexRestorePussyfoot
@LuísSoares IDK if trying to use sudo would help? AKA, was the security message because of not having admin rights? If so try putting sudo mongodump /* rest of code */.Azikiwe
how to export dump from a remote machine ?Industry
@SangramBadi This should work: --host <hostname><:port>, -h <hostname><:port>. You can find more information at docs.mongodb.com/manual/reference/program/mongodumpOssicle
@JulienFr This can also be exported as JSON instead of BSON: techoverflow.net/2018/06/04/… As noted in this document, however: "...some datatypes that can be stored in MongoDB can only be represented in BSON – so in some cases, information may be lost by exporting to JSON."Veedis
I noticed that if I just run the mongdump to a folder it'll create a ton of json files , 1 for each collection ... so if you'd like to keep it simpler , I'd suggest to export it as .gz file below is the command : mongodump --host 127.0.0.1 --port 27017 --username userx --password password01 --authenticationDatabase admin --archive=backup.gz --gzipChirrup
I struggled to make it work so here is a full command that worked for me mongodump --verbose --uri="mongodb+srv://example.mongodb.net" --username=myuser -d mydbname -o mongodb/. Keep in mind this will prompt you for a passwordErvin
what's the alternative for big data storages?Faviolafavonian
Thanks alot buddy ... helped me save a lot of time !Brower
H
79

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
Hurley answered 25/11, 2012 at 11:41 Comment(5)
To import: for file in *.json; do c=${file#*exp_yourdbname_}; c=${c%.json}; mongoimport --db yourdbname --collection "${c}" --file "${file}"; doneSinistrad
i want to import .csv using batch script, do u have any idea?Roscoe
What I could install to use mongo command? Tks.Antimagnetic
Install the mongo javascript CLI here by selecting Community Edition mongodb.com/try/download/communityIdyllist
Replace by mongosh. And replace grep '_' by grep '_' | grep -v ':' to filter stuff.Wylie
P
72

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:[email protected]/mytestdb" -o ./mongo-backup

Remote restore

mongorestore --uri "mongodb+srv://Admin:[email protected]/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.
Parthenogenesis answered 12/1, 2022 at 12:42 Comment(1)
This worked for me. Earlier I was using mongoexport on server with no luck. Then I switched to local computer and used mongodump with the connection string, without the password and it worked. mongodump --uri "mongodb+srv://[email protected]/database_name" it will prompt you for the password, do not include it in the uri string. I had to run this as admin because of permission issues/access denied.Unmask
M
46

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
Mortie answered 4/2, 2016 at 12:48 Comment(2)
I did mongodump -d mongo -o path\to\Desktop\blog and I get a SyntaxError: missing ; before statement from the CMD. :(Liz
@RazvanZamfir install mongodb database tools: mongodb.com/try/download/database-tools set it on your Env Variables. Then run mongodump directly on cmd, not on mongosh shellWholly
M
37

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
Myasthenia answered 2/3, 2018 at 6:10 Comment(0)
C
25

Please let us know where you have installed your Mongo DB? (either in Ubuntu or in Windows)

  • For Windows:
  1. 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.

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

  3. Visit https://www.youtube.com/watch?v=hOCp3Jv6yKo for more details.

  • For Ubuntu:
  1. Login to your terminal where Mongo DB is installed and make sure you are able to connect to your Mongo DB.

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

  3. Visit https://www.youtube.com/watch?v=5Fwd2ZB86gg for more details.

Cleruchy answered 3/11, 2015 at 8:10 Comment(1)
Great, this only works for localhostGlimpse
P
18

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
Prehensile answered 21/10, 2017 at 6:55 Comment(2)
This also works the same: mongodump --uri="mongodb://YOUR_USER_ID:YOUR_PASSWORD@YOUR_HOST_IP/YOUR_DB_NAME" --out /target/folder/pathWhither
--authenticationDatabase admin when requiredHorbal
G
16

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.

Graniela answered 27/2, 2017 at 0:42 Comment(2)
Thanks for answering the exact question that was asked, that was very helpful for me!Jaela
The answer is appropriate enough for the question. The usecase for this command is best only for development migrations. Due to the fact that JSON or CSV cannot handle all data format the BSON can, which the mongodump/mongorestore tools can. Could be improved to have the mongoimport statement as well. I used it to migrate data down from mongo v4.2 to v4.0. Aligning with what you stated in your last paragraphBergerac
W
14

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

Weston answered 22/8, 2019 at 16:23 Comment(0)
S
12

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
Stafani answered 23/1, 2016 at 10:56 Comment(2)
This solution is the best because it properly answers the original question.Sniffle
Note that this does not reliably preserve all rich BSON data types, because JSON can only represent a subset of the types supported by BSON. Use mongodump and mongorestore as described in MongoDB Backup Methods for this kind of functionality. (docs)Forthcoming
W
11

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
Whither answered 3/10, 2020 at 13:58 Comment(0)
F
10

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.

Frye answered 31/8, 2012 at 12:29 Comment(0)
P
9

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
Platonic answered 28/11, 2012 at 21:3 Comment(2)
This is nice, but you would probably want the out.scan regex to be non-greedy. out.scan(/\".+?\"/).map { |s| s.gsub('"', '') }Informality
What I could install to use mongo command? Tks.Antimagnetic
P
9

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 [email protected]:~

then from the parent dir of the dump simply:

mongorestore 

and that imported the database.

assuming mongodb service is running of course.

Protoplast answered 10/1, 2014 at 11:7 Comment(0)
S
8

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.

Schexnayder answered 3/3, 2013 at 23:50 Comment(2)
What I could install to use mongo command? Tks.Antimagnetic
This was a long time ago... but it was just the MongoDB shell. mongodb.com/try/download/shellSchexnayder
A
7

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;
Allergy answered 31/12, 2013 at 21:54 Comment(0)
P
7

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

Podvin answered 5/9, 2014 at 21:9 Comment(1)
The Best and non-complicatedmethod!!Missi
F
6

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}
Facing answered 23/11, 2017 at 10:38 Comment(1)
for more clarity use following info docs.mongodb.com/manual/reference/program/mongodumpFacing
A
3

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
Anisette answered 30/5, 2013 at 13:9 Comment(0)
S
3

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.

Samford answered 27/3, 2016 at 17:32 Comment(0)
V
3

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

Vandavandal answered 19/1, 2021 at 5:5 Comment(0)
T
3

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/

Toogood answered 15/4, 2021 at 8:20 Comment(0)
E
3

This is the simplest technique to achieve your aim.

mongodump -d db_name -o path/filename.json

Epicrisis answered 27/5, 2022 at 17:16 Comment(0)
C
2

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.

Chacma answered 24/3, 2014 at 17:44 Comment(0)
M
2
#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
Maryjanemaryjo answered 3/5, 2018 at 6:32 Comment(0)
A
2

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
Alboran answered 8/2, 2019 at 14:34 Comment(0)
J
2

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
Jennyjeno answered 30/9, 2020 at 10:30 Comment(1)
This works. And the command line is simple.Shimkus
R
1

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
Retardant answered 10/4, 2019 at 18:42 Comment(0)
C
0
  1. Open the Connection
  2. Start the server
  3. 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)
Colangelo answered 6/5, 2014 at 10:13 Comment(2)
It's mongoexport for exportCryptoanalysis
The question is about exporting all collections.Imogeneimojean
D
0

For dump, your DB fallow the below CMD

   mongodump -d <your d name> -o <dump path>
Ex:mongodump -d qualetics -o D:\dbpackup\qualetics
Depreciation answered 3/5, 2019 at 7:2 Comment(0)
I
0

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

Izanagi answered 28/7, 2020 at 17:14 Comment(0)
E
0

This is the bash script I used to achieve the result. The script is generalized to 4 inputs (host url, database, username, and password), so it can be used on any mongo database.

dburl=$1
username=$3
password=$4
db=$2

mongoAccess=mongodb+srv://$username:$password@$dburl/$db

Collections=$(mongo $mongoAccess --quiet --eval "db.getCollectionNames()" | sed 's/,/ /g' | tail +6)

#echo $Collections

for col in $Collections
do
    if [ "$col" = "[" ] || [ "$col" = "]" ]
    then
        continue
    else
        echo "Exporting $col"
        mongoexport --uri $mongoAccess --collection=$col --type json --out output-$col.json
    fi
    
done
Edris answered 8/5, 2021 at 2:14 Comment(0)
S
0

My fellow developer @Mentor Reka is correct but i want to spoon feed it to new people to mongodb.

Note: This is for mongodb local host.

  1. Download MongoDB Command Line Database Tools Download
  2. Extract the zip file somewhere and add the .../bin path into your system environment
  3. open you terminal and write this mongodump --host localhost --port 27017

Node: wherever your .../bin path is it create a file name dump and exports all your data there. If you want to export in specific path use this: mongodump --host localhost --port 27017 --out /path/to/your/directory

Shekinah answered 14/4, 2024 at 14:13 Comment(0)
G
-2

Export The whole Mongo DB just by this commnad

mongoexport –db database_name –collection collection_name –out path_or_filename.json
Gupta answered 7/6, 2022 at 13:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.