www.codewall.co.uk
Open in
urlscan Pro
91.238.160.176
Public Scan
URL:
https://www.codewall.co.uk/mongodb-beginner-tutorial-with-compass-gui-the-mongo-shell-cli/
Submission: On January 15 via manual from US — Scanned from GB
Submission: On January 15 via manual from US — Scanned from GB
Form analysis
3 forms found in the DOMGET https://www.codewall.co.uk/
<form role="search" method="get" class="search-form" action="https://www.codewall.co.uk/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s">
</label>
<input type="submit" class="search-submit" value="Search">
</form>
POST https://www.codewall.co.uk/wp-comments-post.php
<form action="https://www.codewall.co.uk/wp-comments-post.php" method="post" id="commentform" class="comment-form" novalidate="">
<p class="comment-form-comment"><label for="comment">Comment <span class="required">*</span></label> <textarea autocomplete="new-password" id="comment" name="ce29d519a9" cols="45" rows="8" maxlength="65525" required=""></textarea><textarea
id="a6e23e03617f55047ab4e49f1856c50d" aria-label="hp-comment" aria-hidden="true" name="comment" autocomplete="new-password"
style="padding:0 !important;clip:rect(1px, 1px, 1px, 1px) !important;position:absolute !important;white-space:nowrap !important;height:1px !important;width:1px !important;overflow:hidden !important;" tabindex="-1"></textarea>
<script data-noptimize="">
document.getElementById("comment").setAttribute("id", "a6e23e03617f55047ab4e49f1856c50d");
document.getElementById("ce29d519a9").setAttribute("id", "comment");
</script>
</p>
<p class="comment-form-author"><label for="author">Name</label> <input id="author" name="author" type="text" value="" size="30" maxlength="245" autocomplete="name"></p>
<p class="form-submit"><input name="submit" type="submit" id="submit" class="submit" value="Post Comment"> <input type="hidden" name="comment_post_ID" value="4692" id="comment_post_ID">
<input type="hidden" name="comment_parent" id="comment_parent" value="0">
</p>
</form>
GET https://www.codewall.co.uk/
<form role="search" method="get" class="search-form" action="https://www.codewall.co.uk/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s">
</label>
<input type="submit" class="search-submit" value="Search">
</form>
Text Content
WE VALUE YOUR PRIVACY We and our partners store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may access more detailed information and change your preferences before consenting or to refuse consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy. MORE OPTIONSAGREE Skip to content { } CodeWall * Categories * CSS * DevWall * IDEs * Resources * HTML * JavaScript * Laravel * NodeJS * PHP * GraphQL * Sponsored * Privacy Policy * Contact Us * About * Courses * Beginner Data Visualisations Course * Write For Us Search for: December 1, 2019 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 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 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. 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. 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. 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. 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. 21. Make sure you are using the peopledb database, see Figure 21. 22. Use the command in CodeBlock 3 to change the salary of the person with the email of west@randatmail.com. 23. The response returned should give you an acknowledgment that the document was modified. See Figure 25. 24. 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. 21. Make sure you are using the peopledb database, see Figure 21. 22. Enter the following command to delete the document that has the email of j.west@randatmail.com – people.deleteOne({email: “j.west@randatmail.com” }) 23. Mongo should give a JSON response notifying the deletion was successful. See Figure 26. 24. 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 Copy Selecting all fields when executed. With projection parameters, it could be like the following SELECT field1, field2 from tbl Copy 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. 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 – 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. 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 Copy 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. 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. 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 Copy 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. 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. 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. 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 Copy 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 4. Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin. 5. In this folder, there will be a program called mongodump.exe – This is the engine that will backup the database. 6. 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). 7. Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or replace with your own path. 8. Type mongodump –host localhost –port 27017 –db peopledb 9. See Figure 52 for the response. 10. 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 11. Open the next folder inside of it, which should be your Database name that you backed up. 12. 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. 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. 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 4. Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin. 5. In this folder, there will be a program called mongorestore.exe – This is the engine that will restore a database. 6. 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). 7. Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or replace with your own path. 8. Type the command mongorestore --db peopledbduplicate dump/peopledb 9. See the output response in Figure 55. 10. Now connect to mongo with a new command prompt. 11. Type use peopledbduplicate 12. 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. 4. Locate the MongoDB installation /bin folder. For example, C:\Program Files\MongoDB\Server\4.0\bin. 5. Make sure that mongoimport.exe exists. 6. 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). 7. Type cd C:\Program Files\MongoDB\Server\4.0\bin — Or the path of your bin folder 8. 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) 9. Press enter. See Figure 57 for the response after import. 10. Now connect to mongo with a new command prompt. 11. Type use peopledb 12. 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. 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! The Author: Dan Englishby View all posts by Dan Englishby @DanEnglishby Posted in DevWall, MongoDB POST NAVIGATION Previous: What is Kubernetes & what is it used for? Next: GraphQL – hot trend or new standard? LEAVE A REPLY CANCEL REPLY Comment * Name Search for: Copyright 2023 Code Wall. All rights reserved.