MongoDB Beginner Tutorial With Compass GUI & The Mongo Shell CLI

Contents

Introduction

NoSQL is an emerging database technology that provides a non-relational structure of data. In this following document, key factors of getting started with NoSQL with a database container of MongoDB will be explored. In addition to installing and utilizing MongoDB, another piece of software will be used in Tandem with it too. Namely, Compass, MongoDB’s official GUI.

Installation Guide

Pre-requisites

  • Internet Connection
  • Windows Operating System PC/Laptop

MongoDB Setup & Connecting To DB

Downloading MongoDB

To download the latest version of MongoDB, follow the steps below.

Installing MongoDB & Connecting

To install MongoDB onto your computer/server follow the steps below.

Step 1

  1. Locate and open the downloaded installation file.
  2. Double click and open.
  3. See the images below with arrow prompts to install.

figure 1

Figure 1. MongoDB SetupWizard Page1

figure 2

Figure 2. MongoDB SetupWizard Page2

figure 3

Figure 3. MongoDB SetupWizard Page3

Step 2

For this tutorial, MongoDB will be installed under the Network Service user, but alternatively, you can specify a local or domain user if required. For the latter, you must provide an Account Domain and Account Password.

  1. Tick Install MongoDB as a service (This will ensure that MongoDB is online/running each time the computer is booted) Otherwise, it would need to be started manually.
  2. Tick run service as Network Service User.
  3. Leave the default service name of MongoDB so it’s easily recognized.
  4. Leave default data and log directory intact unless you must have it somewhere different.
  5. Click next.
  6. Make sure Install MongoDB Compass is unticked, as this is to be installed manually later.
  7. Click next.
  8. Click Install.
  9. Wait for install to complete and click finish.
  10. Finally, open TaskManager and click the services tab or use windows key + R and type services.msc
  11. Try and locate the MongoDB service instance to make sure the installation was a success. See figure 4.

figure 4

Figure 4. Services. MongoDB

Step 3

Note: If you want to undertake a more advanced setup to access the mongo shell, see Page 45, Advanced MongoDB CLI Setup (Windows OS Only).

  1. Open the command prompt on your computer.
  2. Enter the following command – cd C:\Program Files\MongoDB\Server\4.0\bin (Or replace with the path of the MongoDB installation bin folder)
  3. Now type the following command – mongo
  4. You will now be connected to the MongoDB instance on the local machine. See the following reference on the mongo shell.

 

Compass for MongoDB Setup & Connecting To DB

Downloading Compass for MongoDB

Follow the steps below to download the free, community edition of Compass.

  1. Go to the following download page URL for Compass https://www.mongodb.com/download-center/compass?jmp=docs
  2. Pick the Community Edition Stable version from the drop-down.
  3. Select Windows 64-bit (7+) from the platforms dropdown.
  4. Click the download button.
  5. Wait for the download to complete.

Installing Compass for MongoDB

Step 1

  1. Locate and launch the MongoDB Compass installer that was download earlier.
  2. Read the License Agreement and click agree if you are happy with the conditions.
  3. Navigate through the series of how-to panes until you reach the privacy setting window and tick/untick to your preference.
  4. Lastly, click Start Using Compass.

Step 2

You should now be presented with the following page to set up the GUI software and connect to the MongoDB instance.

figure 5

Figure 5. Compass Initial Setup

 

Add the following parameters as follows

  1. Hostname: localhost or Remote ServerIP
  2. Port: 27017
  3. Leave the rest of the fields as their default and press connect.

After these three steps, the following page should have loaded within the software.

figure 6

Figure 6. COMPASS Connected To Host

 

The Data

 

The data that is going to be used for the purpose of this tutorial is a simple data set generated from the cool website https://generatedata.com. The data consists of people, their first and last name, age, email, education, etc. In addition, It’s a flat data set that is perfect for MongoDB.

It’s worth noting here that the Primary Key of id has been removed from the excel data set due to MongoDB’s default functionality of giving each document (row) a unique id of its own.

Link to Excel data file

If you want to use the exact same data file that I have, then download the excel file below.

People.csv

Managing Data With Compass (CRUD)

Creating a Database & Initial Collection

Step 1

  1. Open up MongoDB Compass Community that was installed earlier.
  2. Connect to the MongoDB Server by specifying parameters as below
    1. Hostname: localhost
    2. Port: 27017
  3. Click connect.
  4. From the loaded dashboard click the Create database button.
  5. The create database helper will be loaded, as shown in Figure 7.
  6. Specify the Database Name as peopledb
  7. Specify the Collection Name as people
  8. Click the Create Database button.

 

figure 7

Figure 7. Create Database Helper

Creating documents (data)

Step 1

Locate the People Database under the MyCluster Pane located on the left-hand pane and click it. You will be presented a screen as shown in Figure 8.

 

figure 8

Figure 8. People Database View

 

Step 2

Then progress to click on the earlier created collection, people, the software will then present a new dashboard of functions shown in Figure 9.

figure 9

Figure 9. People Collection Dashboard

Step 3

Now to add some documents (data), proceed by clicking on the Insert Document button to open the insert document helper as shown in Figure 10.

figure 10

Figure 10. Insert Document Helper

 

Using the data from People excel data set, fill out the key-value fields for the first row of data altering the data types with the right-hand dropdowns, after that press the insert button. See figure 11.

figure 11

Figure 11. Insert Document Data Example

 

Step 5

Hover over the newly created document in the data pane, and hit the clone document button, this will replicate the data into another insert pane. From here, simply type in the next row of data from the excel file, no need to specify the field names or data types this time!

Viewing documents (data)

Compass GUI offers two ways to view data, List view (Figure 12) and Table view (Figure 13). To view data or collection of documents, follow the steps below.

  1. Within Compass click the peopledb in the left-hand pane.
  2. Click the collection name People.
  3. The documents will now be visible in the default List View.
  4. If you want to change it to Table view, simply click the Table toggle parallel to the View menu. See Figure 14 with arrow indicators.

figure 12

 

Figure 12. List view of data

figure 13

 

Figure 13. Table view of data

figure 14

Figure 14. View data toggle

 

Updating documents (data)

Editing or updating documents with Compass is straight forward, follow the next steps to utilize the software and update value fields.

  1. Locate the document you want to update and hover over it until the tooltip pops up.
  2. Click the edit document Pencil icon as shown in Figure 15. This will enable the full modification of the document within the viewer.
  3. Double click the value field of the data you want to update, as shown in Figure 16.
  4. Change the data to your requirement and press enter.
  5. You will notice a Document Modified notification will appear, click the update button on this notification to save changes. See Figure 17.

figure 15

 

Figure 15. Edit document icon

figure 16

 

Figure 16. Editing a value

figure 17

Figure 17. Document modified & Update data button

 

Deleting documents (data)

Deleting documents is another simple task with the Compass software and can be done in two clicks of a button. Please follow the next steps to delete a document.

  1. Locate the document you want to update and hover over it until the tooltip pops up.
  2. Click the delete Trash Can icon as shown in Figure 18.
  3. A notification will appear stating the document has been flagged for deletion in red, Click the delete button as shown in Figure 20 and the document will be deleted.

 

figure 18

Figure 18. Delete Document Icon

figure 19

Figure 19. Document Flagged For Deletion Icon

figure 20

Figure 20. Delete document button

Managing Data With MongoDB CLI (CRUD)

Creating a Database

To create a new database with the MongoShell, please make sure you are already connected via the command line, if not see Page 3, Installing MongoDB & Connecting. Or simply follow these steps –

Quick Command Line Connection Recap
  1. Open the command prompt on your computer.
  2. Enter the following command – cd C:\Program Files\MongoDB\Server\4.0\bin (Or replace with the path of the MongoDB installation bin folder)
  3. Now type the following command – mongo
Create the DB
  1. Type use peopledb. (This command creates the peopledb database)
  2. Press enter, see Figure 21 for what should be displayed.

figure 21

Figure 21. Creating database via mongo shell

Creating a collection adding documents (data)

To create a new document and add documents with the MongoShell, please make sure you are already connected via the command line, if not see Page 3, Installing MongoDB & Connecting.

Inserting one document

  1. Make sure you are using the peopledb database (see Figure 21)
  2. Using the command db.people.insertOne() will create the People collection automatically if it does not exist. Between the parenthesis is where the JSON data should go.
  3. Use the CodeBlock 1 below to insert a row of the CSV file dataset.
  4. A JSON response will be returned to the console, displaying the inserted id. See Figure 22.

CodeBlock 1

db.people.insertOne({"firstName":"Grace","lastName":"Nelson","gender":"Female","age":{"$numberInt":"21"},"email":"g.nelson@randatmail.com","education":"Bachelor","salary":{"$numberInt":"5347"},"maritalStatus":"Single"})

figure 22

Figure 22. After insertOne command is used

 

Inserting multiple documents

Rather than inserting documents one method at a time, you can utilise the insertMany() command. Follow the steps below –

  1. Make sure you are using the peopledb database (see Figure 21)
  2. Using the command db.people.insertMany() will create the people collection automatically if it does not exist. Between the parenthesis is where the array of JSON data should go.
  3. Use the CodeBlock 2 below to insert multiple rows of the CSV file dataset.
  4. A JSON response will be returned to the console, displaying the inserted ids. See Figure 23.

CodeBlock 2

db.people.insertMany([{"firstName":"Daryl","lastName":"Johnson","gender":"Male","age":{"$numberInt":"20"},"email":"d.johnson@randatmail.com","education":"Upper Secondary","salary":{"$numberInt":"4450"},"maritalStatus":"Married"},{"firstName":"Justin","lastName":"West","gender":"Male","age":{"$numberInt":"27"},"email":"j.west@randatmail.com","education":"Doctoral","salary":{"$numberInt":"5783"},"maritalStatus":"Married"}])

figure 23

Figure 23. After insertMany() command

Viewing documents (data)

To view data within the MongoShell, please make sure you are already connected via the command line, if not see Page 3, Installing MongoDB & Connecting.

Follow the steps below –

  1. Make sure you are using the peopledb database (see Figure 21)
  2. Type the command db.people.find() and press enter. The documents in the collection will be returned to the console. See Figure 24

figure 24

Figure 24. db.people.find() all results displayed

Updating documents (data)

To update documents with the MongoShell, please make sure you are already connected via the command line, if not see Page 3, Installing MongoDB & Connecting.

Updating a document uses a method called updateOne() which requires multiple parameters in the format of JSON. The first is the criteria or search term to find the document in question, the second is the values we want to set.

  1. Make sure you are using the peopledb database, see Figure 21.
  2. Use the command in CodeBlock 3 to change the salary of the person with the email of west@randatmail.com.
  3. The response returned should give you an acknowledgment that the document was modified. See Figure 25.
  4. Check that the document was updated visually with the following command – db.people.find({email: "j.west@randatmail.com" })

 

CodeBlock 3

db.people.updateOne({ email: "j.west@randatmail.com" }, {  $set: { "salary": 9999 }   } )

 

figure 25

Figure 25. Updating documents with updateOne()

 

Deleting documents (data)

To delete a document from the database with the mongo CLI, please make sure you are already connected via the command line, if not see Page 3, Installing MongoDB & Connecting.

Deleting a document uses a method called updateOne() which takes up to 3 parameters but, for this example, we will only be using one; filter.

  1. Make sure you are using the peopledb database, see Figure 21.
  2. Enter the following command to delete the document that has the email of j.west@randatmail.com – people.deleteOne({email: “j.west@randatmail.com” })
  3. Mongo should give a JSON response notifying the deletion was successful. See Figure 26.
  4. Check to see if the document above still exists by using the following command – people.find({email: “j.west@randatmail.com” }) and you should see nothing returned from mongo.

 

figure 26

Figure 26. Response after deleteOne() method utilised

Advanced functionality with MongoDB

Projection

Projections are a way of overriding the default way of how MongoDB returns data via a query. Using a projection enables customization of how the data is returned or as otherwise put, what fields are returned.

 

For example, MongoDB will, by default be similar to the following query in SQL

SELECT * from tbl

Selecting all fields when executed.

With projection parameters, it could be like the following

SELECT field1, field2 from tbl

Specifying specific fields to be returned in the result set.

 

With Compass

Using the Compass query bar, you can specify projection fields easily. Following the steps below to perform a projection query on the collection.

  1. Locate the database and collection of documents you want to query in the left-hand pane and click it.
  2. After the view is loaded locate the query bar and press the options button as shown in Figure 27 and click it.
  3. Four options will now appear on the left-hand side, one of these is Project.
  4. Fill out fields that you want to return in the result set in JSON format where the first value in the field and the second is a Boolean 1 or 0 to show the field or not. For example {email : 1}
  5. After filling out the JSON within the project option, click the find button as shown in Figure 28.
  6. The result set returned will now be displayed in the list view below the query bar. See Figure 29 for an example.

figure 27

Figure 27. Query bar options button

figure 28

Figure 28. Find button

figure 29

Figure 29. Projected result set

 

With MongoDB CLI

Projection in the Mongo shell is done with JSON projection parameters passed into the find() method. By specifying a query and secondly, field names and an integer (1 to show and 0 to hide) we can utilize projection.

See the following steps –

  1. Connect to MongoDB instance with the CLI.
  2. Type use peopledb
  3. Type db.people.find({}, {email : 1})
  4. Notice the first empty object parameter in the method above, as we do not want to specify any criteria, in particular, just simply ask for all results instead.
  5. Also, notice the default behavior of the output, the _id field is also included without request.
  6. See Figure 30 for the output.

figure 30

Figure 30. Example Projection Query

Sort

Sorting of data (documents) can be utilized by using the Sort option which takes a field name and the ascending or descending parameter in the format of a number. 1 for Ascending and -1 for descending.

For example, sorting is exactly similar to how you would sort in SQL. See the query below.

SELECT

*

FROM

TBL

ORDER BY

age

ASC

With Compass

See the following steps to perform a sort in a query on collections.

  1. Locate the database and collection of documents you want to query in the left-hand pane and click it.
  2. After the view is loaded locate the query bar and press the options button as shown in Figure 21 and click it.
  3. Four options will now appear on the left-hand side, one of these is Sort.
  4. In the sort option bar enter the parameters in the format of JSON. For example {age: -1}
  5. Press the find button and you will see the document view now be ordered by length descending. See figure 31 for the result view.

figure 31

Figure 31. Results after sort by descending length

With MongoDB CLI

The sort method can be chained to a find method, making it extremely understandable and in opinion, better than executing within compass. The integer supplied acts the same as it does in Compass too, 1 for ascending and -1 for descending.

See the following steps –

  1. Connect to MongoDB instance with the CLI.
  2. Type use peopledb
  3. Type people.find({}, {age : 1}).sort({age: -1}) for descending result.
  4. Type people.find({}, {age : 1}).sort({age: 1}) for ascending result.
  5. See Figure 32 for results sorted by age.

figure 32

Figure 32. Sorting results

Skip

Skip serves the purpose of skipping x number of documents during a query search, by specifying an integer, the MongoDB will skip this amount and return the results next in the collection.

For example, you can execute this command in SQL too. See the following SQL code.

SELECT

*

FROM

TBL

SKIP

1

 

With Compass

To skip documents when executing a query, use the following steps for Compass.

  1. Locate the database and collection of documents you want to query in the left-hand pane and click it.
  2. Click the options button on the query bar and look to the bottom right of the dropped down box, parallel to collation. Here you will find the Skip option. See Figure 33.
  3. Enter an integer, for this tutorial the number 1 will be used.
  4. Click the find button and you will see the result set with the first two collections missing. See Figure 34.

figure 33

Figure 33. Skip option

figure 34

Figure 34. Skip 1 document result set

 

With MongoDB CLI

Again, this method can be chained to existing methods already in the command line, for this example we will use the commands for both the Find and Sort tutorials.

  1. Connect to MongoDB instance with the CLI.
  2. Type use peopledb
  3. Type people.find({}, {email : 1}).sort({age: -1}).skip(1) for descending result that skips the first document, see Figure 35 for an example.
  4. Alternatively use people.find().skip(1) to request all documents, skipping the first document.

figure 35

Figure 35. Skip method example

Limit

Limit is a filter to limit the number of results returned, this can be any number you desire and can serve really good purposes in some use cases.

SQL offers the very same functionality, see the example below, the returned result set would be one row only.

SELECT

*

FROM

TBL

LIMIT 1

With Compass

To skip documents when executing a query, use the following steps for Compass.

  1. Locate the database and collection of documents you want to query in the left hand pane and click it.
  2. Click the options button on the query bar and look to the bottom right of the dropped down box, parallel to collation. Here you will find the limit option. See Figure 26.
  3. Enter an integer, for this tutorial the number 1 will be used.
  4. Click the find button and you will only see one document in the result view. See Figure 27.

figure 36

Figure 36. Limit option

figure 37

Figure 37. Limit 1 result set

 

With MongoDB CLI

The Limit method is highly similar to the Skip method, it requires a single integer and again, it can be chained, see the following steps.

  1. Connect to MongoDB instance with the CLI.
  2. Type use peopledb
  3. Type people.find({}, {email : 1}).sort({age: -1}).skip(1).limit(1) See Figure 38 for an example
  4. Alternatively, you can use skip without chaining to all the methods above. Use the command people.find().limit(1) to retrieve the first document in the collection.

figure 38

Figure 38. Limit method example

Indexing

Just like in SQL server, MongoDB can place indexes on specific fields too. This helps speed up queries but at the same time can add more hard-disk usage with the more indexes utilized.

 

With Compass

By using Compass GUI, indexes can be added to fields in the database’s collections. See the following steps to utilize indexing.

  1. Locate the database and collection you want to place an index on and click it.
  2. From the initial collection dashboard look to the top of the view and find the Indexes tab as shown in Figure 39 and click it.
  3. Next, click the green Create Index button, as shown in Figure 40.
  4. From the modal popup, enter an index name, something of descriptive purpose to the field you want to index. For this example, ageIndex.
  5. Select the field you want to index, for this example, age was selected.
  6. Choose ASC from the index type dropdown. (MongoDB, Index Types, 2018).
  7. Click the create button, see Figure 41.
  8. You will now be able to see the index within the indexes tab view. See Figure 42.

figure 39

 

Figure 39. Index Tab Location

figure 40

 

Figure 40. Start Creating Index Button

figure 41

Figure 41. Create Field Index Button

figure 42

Figure 42. Indexes View After Index Creation

 

With MongoDB CLI

Creating an index is executed with the following method createIndex(), it takes two parameters, the first being specifying the fields that you want to index and the second is specifically for index options which you can see more detail in the documentation.

  1. Connect to MongoDB instance with the CLI.
  2. Type use peopledb
  3. Type people.createIndex({age: 1}) to place an index on the age field.
  4. See Figure 43 for the successful index creation response.

figure 43

Figure 43. createIndex() response

Aggregation

Aggregation in MongoDB is similar to SQL Server aggregation functions like Group By or Sum. Mongo offers 3 prominent options for aggregation; Aggregation Pipeline, Map-Reduce and Single Purpose Aggregation. See the following reference for fine detail on the above-listed methodologies.

With Compass

Compass GUI comes out-of-the-box prepared for aggregation and has its own tab within the collections dashboard. See the steps below to perform a simple aggregation of counting by specific criteria.

  1. Locate the database and collection you want to perform aggregation on and click it, in this case the peopledb DB & people collection.
  2. Locate the Aggregation tab towards the top of the view and click it. See Figure 44 for the location of the tab.
  3. Once the aggregation tab has loaded, enter a Pipeline name, for this example use Count Of Males Pipeline.
  4. Then locate the aggregation stage widget as shown in Figure 45.
  5. Click the select drop down and pick the $match operator, this will load the initial format requirements to the window. See Figure 46.
  6. Within this window, enter a key and value like the following – { gender: “Male” }
  7. Once this is filled out, you will notice the output window on the right displaying only documents with the Gender of ‘Male’. See Figure 47.
  8. Now to add the Count aggregation, to start this, click the Add Stage button underneath the $match query.
  9. Again, from the new stage’s dropdown, select $count.
  10. This JSON blueprint requires a key field only, what you want this count field to be named. Name it malePeopleCount, keeping apostrophes intact.
  11. The output window on the right of this stage will then load the result. See figure 48.
  12. Finally, save the pipeline with the Save Pipeline button at the top of the aggregation view. – This will allow you to preload this aggregation functionality for quick use another time.

 

figure 44

Figure 44. Aggregations tab

 

figure 45

Figure 45. Aggregation Stage Widget

 

figure 46

 

Figure 46. $Match operator JSON

figure 47

 

Figure 47. $match output

figure 48

Figure 48. $match & $count output

 

With MongoDB CLI

The aggregate() function of the Mongo Shell provides many possibilities for aggregation, it allows multiple instances of its aggregating parameters. In this example, a query for the count of all instances of documents with a specific gender.

  1. Connect to MongoDB instance with the CLI.
  2. Type use peopledb
  3. Type the following command people.aggregate([{ $match: { gender: “Male” } }, {“$group” : {_id:”$gender”, count:{$sum:1}}}])
  4. See Figure 49 for the output of the above command.

figure 49

Figure 49. Aggregation, group and count

BackUp

With Compass

Currently, the only method of backing up from the Compass software is to export data at collection level. See the following steps to execute an export.

  1. Locate the database and collection you want to export. For this tutorial, people was used.
  2. Click the collection dropdown at the top of the window as displayed in Figure 50.
  3. Click export collection.
  4. Turn the Export Full Collection toggle on.
  5. Select JSON or CSV (For this example, JSON was selected)
  6. Select the path and type a filename where you want to export the data to go to.
  7. Click the export button, see Figure 51.
  8. The data will be exported in JSON format.

figure 50

Figure 50. Collection dropdown

figure 51

Figure 51. Export Data Button

 

 

With MongoDB CLI

Mongo comes out-of-the-box with a special engine to back up the database, but it may be wise to use a third-party tool to do this to prevent affecting performance. Nevertheless, the following steps show how to back up a MongoDB database.

  1. Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin.
  2. In this folder, there will be a program called mongodump.exe – This is the engine that will backup the database.
  3. Open the command line prompt as administrator (Right click -> run as administrator) to make sure the CLI has utmost access to create the backup file).
  4. Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or replace with your own path.
  5. Type mongodump –host localhost –port 27017 –db peopledb
  6. See Figure 52 for the response.
  7. Check inside the folder C:\Program Files\MongoDB\Server\4.0\bin (or your own path) for a folder named dump, which should have been created and open it
  8. Open the next folder inside of it, which should be your Database name that you backed up.
  9. Inside are the backup files from the mongodump command. See an example of the files in this zip file.

Above parameters explained

  • –host = Hostname, e.g.: localhost or remote host address.
  • –port = Port number, e.g.: 27010 or remote port number.
  • –db = Database name, in this case peopledb or alternatively one of your own.

figure 52

Figure 52. mongodump output

Restore

With Compass

Currently, the only method of backing up from the Compass software is to import data at collection level. See the following steps to execute an import.

  1. Locate the database and click create collection – Call it peopleDuplicate.
  2. Click the peopleDuplicate collection then click the collection dropdown at the top of the window as displayed in Figure 53.
  3. Click the import data option.
  4. Select JSON or CSV (For this example, JSON is used).
  5. Browse to find the file you want to import, in this case, the data that was exported earlier will be used.
  6. Click the import button, see Figure 53.
  7. The data will now be imported into the duplicated collection. See Figure 54.

figure 53

Figure 53. Collection Dropdown & Import Button

figure 54

Figure 54. Collection after import

 

With MongoDB CLI

In this example of restoring with the Mongo engine, the backup that was made with mongodump in the backup tutorial section.

Alternatively, if you didn’t use the backup section, grab the files here. – Add the files to the MongoDB bin folder in a folder named ‘dump’ and in a subfolder named peopledb. So, for example – C:\Program Files\MongoDB\Server\4.0\bin\dump\peopledb

  1. Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin.
  2. In this folder, there will be a program called mongorestore.exe – This is the engine that will restore a database.
  3. Open the command line prompt as administrator (Right click -> run as administrator) to make sure the CLI has the utmost access to create the backup file).
  4. Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or replace with your own path.
  5. Type the command mongorestore --db peopledbduplicate dump/peopledb
  6. See the output response in Figure 55.
  7. Now connect to mongo with a new command prompt.
  8. Type use peopledbduplicate
  9. Type db.people.find() – See Figure 56 for the documents in the newly restored People collection.

 

The parameters for mongorestore above

  • –db = Database name for import/restore
  • Dump/exportedFolder = the command to specify the dump folder inside the /bin folder.

 

figure 55

Figure 55. Output/Response after mongorestore

figure 56

Figure 56. People collection output after restore from dump

 

Import With mongoimport.exe

With the mongoimport exe available to use within the MongoDB installation, it is possible to import data in CSV, TSV or JSON format. In this example, the data set specified at the beginning of the tutorial will be imported into the mongo database. Note: The data set must be saved as a .csv file.

  1. Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin.
  2. Make sure that mongoimport.exe exists.
  3. Open the command line prompt as administrator (Right click -> run as administrator) to make sure the CLI has the utmost access to create the backup file).
  4. Type cd C:\Program Files\MongoDB\Server\4.0\bin   — Or the path of your bin folder
  5. Use the following command – mongoimport –db peopledb –collection peopleDuplicate –type csv –headerline –file C:\Users\DWEPr\Desktop\people.csv ( –file will be the full path to your CSV file)
  6. Press enter. See Figure 57 for the response after import.
  7. Now connect to mongo with a new command prompt.
  8. Type use peopledb
  9. Type db.peopleDuplicate.find(). See Figure 58 for the documents in the newly restored peopleDuplicate collection.

 

Parameters for mongoimport explained

  • –db = Database name you want to import into
  • –collection = The name of the collection you want to create/import into.
  • –type = type of file, in this case, CSV
  • –headerline = Instructs the engine to use the first line of the CSV as the field names.
  • –file = the full path to the CSV file for import.

figure 57

Figure 57. Output after import CSV

figure 58

Figure 58. Collection after CSV import

Advanced MongoDB CLI Setup (Windows OS Only)

To save time whilst using the command line, you can set an Environment Variable in the form of a path to your mongo engine. This will prevent specifying the full folder path of the engine every time you boot the command prompt and rather just be able to type ‘mongo’. See the following steps to set it up.

In addition to the ability to use mongo quickly, other engines like mongodump and mongorestore will also be available from the CLI too, simply by typing them.

  1. Go to control panel
  2. Click System and find Advanced System Settings and open it.
  3. Click environment variables.
  4. Find the user variables window and look for ‘Path’ if it’s not already there, then you will need to follow these sub-steps
    1. Click New
    2. Enter Path as the variable name
    3. Enter cd C:\Program Files\MongoDB\Server\4.0\bin as the variable value (or the path to your mongo bin folder).
    4. Click Ok, then Ok again.
  5. If the path does exist, click it and press edit.
  6. Click new on the right-hand side and enter the following – cd C:\Program Files\MongoDB\Server\4.0\bin (or the path to your bin folder)
  7. Click Ok, then Ok again.
  8. Finally, open up the command prompt and type mongo
  9. You should now be connected to the mongo shell!

 

 

SHARE ON

The Author: Dan Englishby

MongoDB Beginner Tutorial With Compass GUI & The Mongo Shell CLI

You May Also Like

Leave a Reply

Your email address will not be published.