How to import and export a MongoDB database on Ubuntu 20.04?
Overview
MongoDB database is created and managed by MongoDB. It is widely recognized as a NoSQL database system renowned for its scalability, robustness, dependability, and user-friendly nature.
This tutorial aims to demonstrate the process of importing and exporting MongoDB databases, emphasizing that these operations involve handling data in format that humans can easily read and is compatible with various other software applications.
Prerequisites
There are certain prerequisites that need to be met before you begin:
A server running Ubuntu version 20.04 with sudo access and a UFW firewall is turned on.
Comprehending the disparities between JSON data and BSON data.
Get Started
Step 1 - Import data into MongoDB
For importing data into MongoDB, let's use a widely used MongoDB database containing restaurant's information. You can download this database in the .json format by running the following wget command:
Once it is downloaded, you will get a file named primer-dataset located in current directory. To import data from the downloaded file into newly created database, newdb and in a collection named restaurants, employ the following command:
To confirm the successful import, establish a connection to newdb database:
Determine the number of documents in restaurants collection by executing the following command:
Retrieve the initial document from restaurants collection using the following query:
To exit, type the following command:
Step 2 - Export data from MongoDB
To extract data from MongoDB, execute the mongoexport command. This command provides the flexibility to perform detailed exports by specifying the database, collection, field and incorporating a query.
Let's consider the collection of restaurants from newdb that we previously imported as an example. The export can be executed in the following way:
In certain situations, it might be necessary to export a specific subset of your database collection. Given the structure as well as data within JSON file of restaurants, our objective is to export all restaurants that fulfill the conditions of being located in Bronx borough as well as specializing in Chinese cuisine. For direct retrieval of information from MongoDB while maintaining an active connection, simply reconnect to database.
Execute the following query:
To exit, enter the following command:
If you prefer to export data using sudo command rather than maintaining a database connection, you can incorporate previous query into mongoexport command in the following manner:
Use the commands cat and less to scan through the data:
Conclusion
We have successfully demonstrated how to import and export a MongoDB Database on Ubuntu 20.04.
Last updated