MongoDB examples of backup restore export import clone operations

  • 2020-05-17 06:51:31
  • OfStack

Database backup, mongodump

Backup all local MongoDB databases:


# mongodump -h 127.0.0.1 --port 27017 -o /root/db/alldb

Backup remote specified database:

# mongodump -h 192.168.1.233 --port 27018 -d yourdb -o /root/db/yourdb

More details on mongodump

Database restore -mongorestore

Restore all databases to MongoDB:


# mongorestore -h 127.0.0.1 --port 27018 /root/db/alldb

Restore the specified database:

# mongorestore --port 27017 -d yourdb /root/db/yourdb

More details on mongorestore
Export collection data -mongoexport

Export the data of the specified collection in the database:


# mongoexport -h 192.168.1.233 --port 27018 -d yourdb -c yourcoll -o /root/yourcoll.json

Export the data of the specified field in the collection. The exported file format is csv:

# mongoexport -d yourdb -c test -f "id,name,score" --csv -o /root/test.csv

Export data according to the conditions:

# mongoexport -d yourdb -c yourcoll -q '{score:{$gt:80}}' -o /root/yourcoll-bk.json

More details on mongoexport

Collection data import -mongoimport

Restore the exported collection data:


# mongoimport -d yourdb -c yourcoll --file /root/yourcoll.json

Import collection data, insert or update existing data:

# mongoimport -d test -c yourcoll --file /root/yourcoll.json --upsert

More details on mongoimport

MongoDB database cloning

Command format:


db.copyDatabase(fromdb, todb, fromhost, username, password)

Copy the specified database locally from remote MongoDB:

# mongo
> db.copyDatabase("yii2", "lyii2", "192.168.0.69")

More details on db.copyDatabase
Cloning of sets

Command format:


db.runCommand({ cloneCollection: "<namespace>", from: "<hostname>", query: { <query> } });

Clone the specified collection from the remote MongoDB to the local database:

# mongo
> db.runCommand({  cloneCollection: "test.user", from: "192.168.0.69", query:{}    })

More details on cloneCollection


Related articles: