MongoDB is one of the most popular NoSQL databases in the world today, frequently employed in a myriad of applications. One of the common operations users perform on MongoDB is exporting and importing data, which is often vital for tasks like backup, migration, or data analysis.
In this article, we will walk you through the process of exporting and importing MongoDB collections using MongoDB's official database tools.
Prerequisites
MongoDB Database Tools: Before starting, you need to download MongoDB's official Database Tools. These tools provide the necessary utilities to perform our required operations. Download it from the following link: MongoDB Database Tools.
Installation Path: After downloading and installing the tools, remember the path. The default installation path for Windows is usually C:\Program Files\MongoDB\Tools\100\bin
. Either add this path to your system's PATH variable or navigate to this directory each time you want to run the commands.
Exporting MongoDB Collections
Exporting allows you to take a snapshot of your data in MongoDB and save it as a backup or for transfer purposes. Here’s how you can export your data:
Open Command Prompt or Terminal: Depending on your operating system, open the Command Prompt (Windows) or Terminal (Mac/Linux).
Navigate to the Directory: If you haven’t added the tools to your PATH, navigate to the directory where the MongoDB tools are installed:
cd C:\Program Files\MongoDB\Tools\100\bin
Run the Export Command: Use the mongodump
utility to export your data. Here's the generic command to execute:
./mongodump --uri "mongodb+srv://USERNAME:PASSWORD@DB_URL/DB_URL?retryWrites=true&w=majority" -o "OUTPUT_PATH"
Replace USERNAME
, PASSWORD
, DB_URL
, and OUTPUT_PATH
with your MongoDB credentials and the desired output directory respectively. It will create a.json
for each collection in the output directory you chosen.
Importing MongoDB Collections
Now that we've seen how to export, let’s look at how to import the data back into MongoDB:
Open Command Prompt or Terminal: As before, open your command interface.
Navigate to the Directory: If not already there, navigate to the MongoDB tools directory.
Run the Import Command: Use the mongorestore utility to import your data. Here's the generic command to execute:
./mongorestore -d production_clone3 "CLONED_DB_PATH"
Replace production_clone3
with your desired database name and CLONED_DB_PATH
with the path to the directory containing the data dump you want to restore.
Conclusion
Exporting and importing MongoDB collections is straightforward with the MongoDB Database Tools. These operations are foundational in managing and migrating data, ensuring data safety, and performing backups. Now that you know how to do it, you can confidently manage your MongoDB datasets with ease.
Top comments (0)