Original Article on : https://www.codewall.co.uk/mongodb-beginner-tutorial-with-compass-gui-the-mongo-shell-cli/
Contents
- Introduction.
- Installation Guide.
- Pre-requisites.
- MongoDB Setup & Connecting To DB.
- Downloading MongoDB.
- Installing MongoDB & Connecting.
- Compass for MongoDB Setup & Connecting To DB.
- Downloading Compass for MongoDB.
- Installing Compass for MongoDB.
- The Data.
- Link to Excel data file.
- Managing Data With Compass (CRUD)
- Creating a Database & Initial Collection.
- Creating documents (data)
- Viewing documents (data)
- Updating documents (data)
- Deleting documents (data)
- Managing Data With MongoDB CLI (CRUD)
- Creating a Database.
- Creating a collection adding documents (data)
- Inserting one document
- Inserting multiple documents.
- Viewing documents (data)
- Updating documents (data)
- Deleting documents (data)
- Advanced functionality with MongoDB.
- Projection.
- Sort
- Skip.
- Limit
- Indexing.
- Aggregation.
- BackUp.
- Restore.
- Import With mongoimport.exe.
- Advanced Data With MongoDB.
- Advanced MongoDB CLI Setup (Windows OS Only)
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.
- Go to https://www.mongodb.com/download-center/community
- Choose the current release from the version dropdown.
- Select Windows 64-bit x64 from the OS dropdown.
- Make sure MSI is the package selected.
- Click download.
Installing MongoDB & Connecting
To install MongoDB onto your computer/server follow the steps below.
Step 1
- Locate and open the downloaded installation file.
- Double click and open.
- See the images below with arrow prompts to install.
Figure 1. MongoDB SetupWizard Page1
Figure 2. MongoDB SetupWizard Page2
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.
- 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.
- Tick run service as Network Service User.
- Leave the default service name of MongoDB so it’s easily recognized.
- Leave default data and log directory intact unless you must have it somewhere different.
- Click next.
- Make sure Install MongoDB Compass is unticked, as this is to be installed manually later.
- Click next.
- Click Install.
- Wait for install to complete and click finish.
- Finally, open TaskManager and click the services tab or use windows key + R and type services.msc
- Try and locate the MongoDB service instance to make sure the installation was a success. See 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).
- Open the command prompt on your computer.
- Enter the following command – cd C:\Program Files\MongoDB\Server\4.0\bin (Or replace with the path of the MongoDB installation bin folder)
- Now type the following command – mongo
- 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.
- Go to the following download page URL for Compass https://www.mongodb.com/download-center/compass?jmp=docs
- Pick the Community Edition Stable version from the drop-down.
- Select Windows 64-bit (7+) from the platforms dropdown.
- Click the download button.
- Wait for the download to complete.
Installing Compass for MongoDB
Step 1
- Locate and launch the MongoDB Compass installer that was download earlier.
- Read the License Agreement and click agree if you are happy with the conditions.
- Navigate through the series of how-to panes until you reach the privacy setting window and tick/untick to your preference.
- 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. Compass Initial Setup
Add the following parameters as follows
- Hostname: localhost or Remote ServerIP
- Port: 27017
- 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. 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.
Managing Data With Compass (CRUD)
Creating a Database & Initial Collection
Step 1
- Open up MongoDB Compass Community that was installed earlier.
- Connect to the MongoDB Server by specifying parameters as below
- Hostname: localhost
- Port: 27017
- Click connect.
- From the loaded dashboard click the Create database button.
- The create database helper will be loaded, as shown in Figure 7.
- Specify the Database Name as peopledb
- Specify the Collection Name as people
- Click the Create Database button.
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. 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. 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. 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. 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.
- Within Compass click the peopledb in the left-hand pane.
- Click the collection name People.
- The documents will now be visible in the default List View.
- 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. List view of data
Figure 13. Table view of data
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.
- Locate the document you want to update and hover over it until the tooltip pops up.
- Click the edit document Pencil icon as shown in Figure 15. This will enable the full modification of the document within the viewer.
- Double click the value field of the data you want to update, as shown in Figure 16.
- Change the data to your requirement and press enter.
- You will notice a Document Modified notification will appear, click the update button on this notification to save changes. See Figure 17.
Figure 15. Edit document icon
Figure 16. Editing a value
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.
- Locate the document you want to update and hover over it until the tooltip pops up.
- Click the delete Trash Can icon as shown in Figure 18.
- 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. Delete Document Icon
Figure 19. Document Flagged For Deletion Icon
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
- Open the command prompt on your computer.
- Enter the following command – cd C:\Program Files\MongoDB\Server\4.0\bin (Or replace with the path of the MongoDB installation bin folder)
- Now type the following command – mongo
Create the DB
- Type use peopledb. (This command creates the peopledb database)
- Press enter, see Figure 21 for what should be displayed.
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
- Make sure you are using the peopledb database (see Figure 21)
- 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.
- Use the CodeBlock 1 below to insert a row of the CSV file dataset.
- 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. 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 –
- Make sure you are using the peopledb database (see Figure 21)
- 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. - Use the CodeBlock 2 below to insert multiple rows of the CSV file dataset.
- 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. 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 –
- Make sure you are using the peopledb database (see Figure 21)
- 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. 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.
- Make sure you are using the peopledb database, see Figure 21.
- Use the command in CodeBlock 3 to change the salary of the person with the email of west@randatmail.com.
- The response returned should give you an acknowledgment that the document was modified. See Figure 25.
- 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. 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.
- Make sure you are using the peopledb database, see Figure 21.
- Enter the following command to delete the document that has the email of j.west@randatmail.com – people.deleteOne({email: “j.west@randatmail.com” })
- Mongo should give a JSON response notifying the deletion was successful. See Figure 26.
- 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. 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.
- Locate the database and collection of documents you want to query in the left-hand pane and click it.
- After the view is loaded locate the query bar and press the options button as shown in Figure 27 and click it.
- Four options will now appear on the left-hand side, one of these is Project.
- 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}
- After filling out the JSON within the project option, click the find button as shown in Figure 28.
- The result set returned will now be displayed in the list view below the query bar. See Figure 29 for an example.
Figure 27. Query bar options button
Figure 28. Find button
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 –
- Connect to MongoDB instance with the CLI.
- Type use peopledb
- Type
db.people.find({}, {email : 1})
- 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.
- Also, notice the default behavior of the output, the _id field is also included without request.
- See Figure 30 for the output.
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.
- Locate the database and collection of documents you want to query in the left-hand pane and click it.
- After the view is loaded locate the query bar and press the options button as shown in Figure 21 and click it.
- Four options will now appear on the left-hand side, one of these is Sort.
- In the sort option bar enter the parameters in the format of JSON. For example {age: -1}
- 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. 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 –
- Connect to MongoDB instance with the CLI.
- Type use peopledb
- Type
people.find({}, {age : 1}).sort({age: -1})
for descending result. - Type
people.find({}, {age : 1}).sort({age: 1})
for ascending result. - See Figure 32 for results sorted by age.
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.
- Locate the database and collection of documents you want to query in the left-hand pane and click it.
- 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.
- Enter an integer, for this tutorial the number 1 will be used.
- Click the find button and you will see the result set with the first two collections missing. See Figure 34.
Figure 33. Skip option
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.
- Connect to MongoDB instance with the CLI.
- Type use peopledb
- Type
people.find({}, {email : 1}).sort({age: -1}).skip(1)
for descending result that skips the first document, see Figure 35 for an example. - Alternatively use people.find().skip(1) to request all documents, skipping the first document.
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.
- Locate the database and collection of documents you want to query in the left hand pane and click it.
- 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.
- Enter an integer, for this tutorial the number 1 will be used.
- Click the find button and you will only see one document in the result view. See Figure 27.
Figure 36. Limit option
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.
- Connect to MongoDB instance with the CLI.
- Type use peopledb
- Type
people.find({}, {email : 1}).sort({age: -1}).skip(1).limit(1)
See Figure 38 for an example - 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. 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.
- Locate the database and collection you want to place an index on and click it.
- 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.
- Next, click the green Create Index button, as shown in Figure 40.
- From the modal popup, enter an index name, something of descriptive purpose to the field you want to index. For this example, ageIndex.
- Select the field you want to index, for this example, age was selected.
- Choose ASC from the index type dropdown*. (MongoDB, Index Types, 2018).*
- Click the create button, see Figure 41.
- You will now be able to see the index within the indexes tab view. See Figure 42.
Figure 39. Index Tab Location
Figure 40. Start Creating Index Button
Figure 41. Create Field Index Button
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.
- Connect to MongoDB instance with the CLI.
- Type use peopledb
- Type
people.createIndex({age: 1})
to place an index on the age field. - See Figure 43 for the successful index creation response.
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.
- Locate the database and collection you want to perform aggregation on and click it, in this case the peopledb DB & people collection.
- Locate the Aggregation tab towards the top of the view and click it. See Figure 44 for the location of the tab.
- Once the aggregation tab has loaded, enter a Pipeline name, for this example use Count Of Males Pipeline.
- Then locate the aggregation stage widget as shown in Figure 45.
- Click the select drop down and pick the $match operator, this will load the initial format requirements to the window. See Figure 46.
- Within this window, enter a key and value like the following – { gender: “Male” }
- 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.
- Now to add the Count aggregation, to start this, click the Add Stage button underneath the $match query.
- Again, from the new stage’s dropdown, select $count.
- This JSON blueprint requires a key field only, what you want this count field to be named. Name it malePeopleCount, keeping apostrophes intact.
- The output window on the right of this stage will then load the result. See figure 48.
- 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. Aggregations tab
Figure 45. Aggregation Stage Widget
Figure 46. $Match operator JSON
Figure 47. $match output
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.
- Connect to MongoDB instance with the CLI.
- Type use peopledb
- Type the following command people.aggregate([{ $match: { gender: “Male” } }, {“$group” : {_id:”$gender”, count:{$sum:1}}}])
- See Figure 49 for the output of the above command.
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.
- Locate the database and collection you want to export. For this tutorial, people was used.
- Click the collection dropdown at the top of the window as displayed in Figure 50.
- Click export collection.
- Turn the Export Full Collection toggle on.
- Select JSON or CSV (For this example, JSON was selected)
- Select the path and type a filename where you want to export the data to go to.
- Click the export button, see Figure 51.
- The data will be exported in JSON format.
Figure 50. Collection dropdown
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.
- Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin.
- In this folder, there will be a program called mongodump.exe – This is the engine that will backup the database.
- 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).
- Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or replace with your own path.
- Type mongodump –host localhost –port 27017 –db peopledb
- See Figure 52 for the response.
- 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
- Open the next folder inside of it, which should be your Database name that you backed up.
- 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. 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.
- Locate the database and click create collection – Call it peopleDuplicate.
- Click the peopleDuplicate collection then click the collection dropdown at the top of the window as displayed in Figure 53.
- Click the import data option.
- Select JSON or CSV (For this example, JSON is used).
- Browse to find the file you want to import, in this case, the data that was exported earlier will be used.
- Click the import button, see Figure 53.
- The data will now be imported into the duplicated collection. See Figure 54.
Figure 53. Collection Dropdown & Import Button
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
- Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin.
- In this folder, there will be a program called mongorestore.exe – This is the engine that will restore a database.
- 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).
- Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or replace with your own path.
- Type the command
mongorestore --db peopledbduplicate dump/peopledb
- See the output response in Figure 55.
- Now connect to mongo with a new command prompt.
- Type use peopledbduplicate
- 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. Output/Response after mongorestore
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.
- Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin.
- Make sure that mongoimport.exe exists.
- 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).
- Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or the path of your bin folder
- 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)
- Press enter. See Figure 57 for the response after import.
- Now connect to mongo with a new command prompt.
- Type use peopledb
- 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. Output after import CSV
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.
- Go to control panel
- Click System and find Advanced System Settings and open it.
- Click environment variables.
- Find the user variables window and look for ‘Path’ if it’s not already there, then you will need to follow these sub-steps
- Click New
- Enter Path as the variable name
- Enter cd C:\Program Files\MongoDB\Server\4.0\bin as the variable value (or the path to your mongo bin folder).
- Click Ok, then Ok again.
- If the path does exist, click it and press edit.
- 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)
- Click Ok, then Ok again.
- Finally, open up the command prompt and type mongo
- You should now be connected to the mongo shell!
Top comments (0)