The author choosesCOVID-19 Relief FundThrough theWrite for DOnationsPlans to accept donations.

Introduction to the

MongoDB is one of the most popular NoSQL database engines. It is known for its scalability, performance, reliability, and ease of use. In this article, we’ll show you how to import and export your MongoDB database.

We should clarify that imports and exports are those operations that process data in a human-readable format, compatible with other software products. In contrast, backup and restore operations create or use MongoDB specific binary data, which preserves the consistency and integrity of your data and its specific MongoDB attributes. Therefore, for migration, it is usually best to use backup and restore as long as the source and target systems are compatible.

Backup, restore, and migration tasks are beyond the scope of this article. For more information, see How to Back up a MongoDB Database on Ubuntu 20.04.

A prerequisite for

To complete this tutorial, you will need the following.

  • Ubuntu 20.04 droplets, set up according to the Ubuntu 20.04 Initial Server Setup Guide, include a Sudo non-root user and a firewall.
  • Install and configure MongoDB using the article “Install MongoDB on Ubuntu 20.04”.
  • Understand the difference between JSON and BSON data in MongoDB. For further discussion, read the first step in our tutorial on backing up, restoring, and migrating MongoDB databases on Ubuntu 20.04 — Using JSON and JSON in MongoDB.

Step 1 — Import the information into MongoDB

To learn how to import information into MongoDB, we’ll use a popular MongoDB sample database for restaurants. It is in.json format and can be downloaded using wget.

wget https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json
Copy the code

Once the download is complete, you should have a file called primer-dataset. Json (12MB in size) in the current directory. Let’s import the data from this file into a new database called newDB and into a collection called Restaurants.

Use mongoimport as follows.

sudo mongoimport --db newdb --collection restaurants --file primer-dataset.json
Copy the code

And it looks something like this.

Output2020-11-11 t19:37:55. 607 + 0000 connected to: Mysql ://localhost/ 2020-11-11t19:37:57.841 +0000 25359 document(s) Imported successfully importCopy the code

As shown in the above command, 25,359 files were imported. Since we don’t have a database named newDB, MongoDB creates it automatically.

Let’s check the import.

Connect to the newly created newDB database.

sudo mongo newdb
Copy the code

You are now connected to the newDB database instance. Notice that your prompt has changed to indicate that you are connected to the database.

Use the command to calculate the files in the restaurant collection.

db.restaurants.count()
Copy the code

The result shows 25,359, which is the number of import documents. For better inspection, you can select the first file from the restaurant collection, as shown below.

db.restaurants.findOne()
Copy the code

And it looks something like this.

[secondary label Output] { "_id" : ObjectId("5fac3d937f12c471b3f26733"), "address" : { "building" : "1007", "coord" : [-73.856077, 40.848447], "Street" : "Morris Park Ave", "Zipcode" : "10462", "Borough" : "Bronx", "Cuisine" : "Bakery", "grades" : [ { "date" : ISODate("2014-03-03T00:00:00Z"), "grade" : "A", "score" : 2 }, ... ] , "name" : "Morris Park Bake Shop", "restaurant_id" : "30075445" }Copy the code

This scrutiny can reveal problems with the file, such as its content, encoding, and so on. The JSON format uses UTF-8 encoding, which should be used for both your exports and imports. Keep this in mind if you are manually editing json files. Otherwise, MongoDB will handle it for you.

To exit the MongoDB prompt, type exit at the prompt.

exit
Copy the code

You will be returned to the normal command prompt as a non-root user.

Step 2 – Export the information from MongoDB

As mentioned earlier, exporting MongoDB information allows you to retrieve a human-readable text file containing the data. By default, information is exported in JSON format. However, you can also export it as CSV (comma-separated values).

To export information from MongoDB, use the command mongoexport. It allows you to do very fine-grained exports, so you can specify a database, a collection, a field, or even a query to export.

A simple Mongoexport is the restaurant set in the newDB database we imported before. This can be done as follows.

sudo mongoexport --db newdb -c restaurants --out newdbexport.json
Copy the code

In the above command, we use –db to specify database -c for the collection and –out for the file to store the data.

For a successful Mongoexport, its output should look like this.

Output2020-11-11 t19:39:57. 595 + 0000 connected to: Mongo: / / localhost / 2020-11-11 T19:39:58. 619 + 0000 [# # # # # # # # # # # # # # #...] Newdb. 16000/25359 (63.1%) of the 2020-11-11 T19 restaurants: 39:58. 871 + 0000 [# # # # # # # # # # # # # # # # # # # # # # # #] newdb. The restaurants 25359/25359 (100.0%) 2020-11-11T19:39:58.871+0000 Exported 25359 RecordsCopy the code

The output above shows that 25,359 files were imported, the same number of imports.

In some cases, you may only need to export a portion of your collection. Given the structure and content of the restaurant JSON file, we exported all the compliant restaurants in the Bronx that served Chinese food. If we want to get this information directly when we connect to MongoDB, connect to the database again.

sudo mongo newdb
Copy the code

Then use the query.

db.restaurants.find( { "borough": "Bronx"."cuisine": "Chinese"})Copy the code

The results will be displayed on the terminal.

Output2020-12-03t01:35:25.366 +0000 Connected to: mongodb://localhost/ 2020-12-03T01:35:25.410+0000 Exported 323 RecordsCopy the code

To exit the MongoDB prompt, type exit.

exit
Copy the code

If you want to export data from the sudo command line instead of connecting to the database, make the previous query part of the mongoexport command by specifying the -q parameter, as shown below.

sudo mongoexport --db newdb -c restaurants -q "{\"borough\": \"Bronx\", \"cuisine\": \"Chinese\"}" --out Bronx_Chinese_retaurants.json
Copy the code

Note that we have bypassed the double quotes with backslashes (\) in the query. Similarly, you need to bypass all other special characters in the query.

If the export is successful, the result should look like this.

Output2020-11-11t19:49:21.727 +0000 Connected to: mongodb:// Localhost / 2020-11-11T19:49:21.765+0000 Exported 323 RecordsCopy the code

The example above shows that 323 records were exported and you can find them in the file we specified.

Use CAT and less to search for data.

cat Bronx_Chinese_retaurants.json | less
Copy the code

Use SPACE to submit data.

Outputdate": {"$date":"2015-01-14T00:00:00Z"},"grade":"Z","score": 36}]."na{"_id": {"$oid":"5fc8402d141f5e54f9054f8d"},"address": {"building":"1236"."coord": [73.8893654, 40.81376179999999]."street":"238 Spofford Ave"."zipcode":"10474"},"borough":"Bronx"."cuisine":"Chinese"."grades": [{"date": {"$date":"2013-12-30T00:00:00Z"},"grade":"A"."score": 8}, {"date": {"$date":"2013-01-08T00:00:00Z"},"grade":"A"."score": 10}, {"date": {"$date":"2012-06-12T00:00:00Z"},"grade":"B"."score": 15}]...Copy the code

Press Q to exit. You can now import and export a MongoDB database.

Abstract

This article has taken you through the basics of importing and exporting information to a MongoDB database. You can read more about how to back up MongoDB databases on Ubuntu 20.04.

You can also consider copying. Replication allows the slave MongoDB server to continue your MongoDB service continuously if you restore the master service after a failure. Part of the copy is the operation log (OPLOG), which records all the changes to your data. You can use this log, like a binary log in MySQL, to restore your data after the last backup. Remember, backups usually take place at night. If you decide to restore the backup at night, you will miss all updates since the last backup.