This article is part of Robert Sheldon's continuing series on Mongo DB. To see all of the items in the series, click here.
Throughout this series, I’ve discussed various ways to work with the documents in a MongoDB collection. If you’ve been following along, you should now have a good sense of how to perform basic create, read, update, and delete (CRUD) operations. As you might recall, much of my focus has been on how to use MongoDB Shell to carry out these operations. This has been especially true when it comes to modifying data. In this article, I focus squarely on the MongoDB Compass GUI, demonstrating features within the interface for working with the documents directly.
Not everyone will want to use the GUI features in Compass to perform CRUD operations, preferring instead to stick with shell commands. Even so, some of you will appreciate how easy it is to use Compass to carry out these operations, especially when performing ad hoc tasks. You might bump up against limitations in the interface, or it might seem a bit clunky at times, but for the most part, you should find the operations fairly straightforward and simple to perform.
To help you become more familiar with the Compass interface, this article demonstrates various ways to insert, update, and delete documents, while providing numerous examples along with way. As with other aspects of MongoDB, you often have multiple options for achieving the same goals, so I’ve tried to provide you with a good overview of possibilities. With that in mind, let’s start digging into the Compass GUI.
Note: For the examples in this article, I used the same MongoDB Atlas and MongoDB Compass environments I used for the previous articles in this series. Refer to the first article for more specifics about setting up these environments.
Inserting documents in a MongoDB collection
The Compass GUI makes it fairly easy to add individual documents to a collection, as you’ll see in the examples to follow. For these examples, I used the hr
database and employees
collection. You can use any test database or collection you want, as long as the collection is empty. You might stick with the hr
database and employees
collection just to keep things simple.
If you worked through the examples in previous articles, you might already have the created the hr
database and employees
collection, and the collection might already contain documents. To use the database and collection for this article, you should launch MongoDB Compass, establish your connection to MongoDB Atlas, and then take one of the following steps:
- If the
hr
database andemployees
collection exist and the collection is empty, you don’t need to do anything else. You’re ready to try out the examples. - If the
hr
database andemployees
collection exist, but the collection contains documents, you should delete them. To delete the documents, open the collection, click the Delete button on the Documents tab of the main window, and then click the Delete x documents button in the Delete x documents dialog box, where x is the number of documents to be deleted. You’ll then need to confirm the deletion. - If the
hr
database exists but does not include theemployees
collection, click the Create collection button (plus sign) to the right of the hr database node in the left panel. In the Create Collection dialog box, type employees in the Collection Name text box and click Create Collection. - If the
hr
database andemployees
collection do not exist, click the Create database button (plus sign) to the right of the Databases node in the left panel. In the Create Database dialog box, type hr in the Database Name text box, type employees in the Collection Name text box, and then click Create Database.
Once you have your database and collection in place, you can start adding documents to the collection. The Compass GUI offers several methods for adding documents, all of which rely on the Insert Document dialog box, as described in the following sections.
Adding individual documents to a collection
click the employees collection node in the left panel to ensure that it is open and is the active collection. On the Documents tab of the main window, click the Add Data button and then click the Insert document option in the popup menu. When the Insert Document dialog box appears, delete the existing text and paste in the following document code:
1 2 3 4 5 6 7 8 9 10 |
{ "_id": 101, "name": "Drew", "location": "Seattle", "division": "Western", "current_emp": true, "yrs_exp": 18, "skills": [ "Csharp", "SQL", "Swift", "C" ], "position": "Senior Developer" } |
After you add your code, the Insert Document dialog box should look similar to the one shown in the following figure. If there are any problems with the code’s syntax, the dialog box will display a message stating that an insert is not permitted while the document contains errors.
Notice that the dialog box displays the name of the database and collection near the top. In this case, the dialog box shows hr.employees, but it will list the name of whichever database and collection you’re using.
Once you’re satisfied with your document code, click the Insert button to add the document to the collection. The Documents tab of the main Compass window should now display the newly added document, as shown in the following figure. In this case, I expanded the skills
array to display the individual values.
The example above added only a single document to the collection, but you can take a similar approach to add multiple documents. The key is to enclose the document definitions in square brackets and separate them with a comma to create an array of documents. For example, the following code adds two documents, both enclosed in a set of square brackets and separated with a comma:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[ { "_id": 102, "name": "Parker", "location": "Portland", "division": "Western", "current_emp": true, "yrs_exp": 14, "position": "Data Scientist" }, { "_id": 103, "name": "Harper", "location": "Chicago", "division": "Western", "current_emp": true, "yrs_exp": 22, "position": "Marketing Manager" } ] |
The code defines a document with an _id
value of 102
and one with an _id
value of 103
. To insert these documents into the employees
collection, launch the Insert Document dialog box as before, delete the existing text, paste in the above code, and then click the Insert button. MongoDB will add both documents to the collection, just like it added one document. The collection should now contain three documents, as shown in the following figure.
Using the Field-by-Field Editor to add documents
The Insert Document dialog box also provides a more interactive way to insert a single document to a collection. This feature, referred to as the Field-by-Field Editor, lets you add the fields and their values one at a time through an interactive grid. The functionality is still a little rough around the edges, and it’s a fairly time-consuming process compared to other approaches, but it could still be useful for some users.
Let me demonstrate how it works. As in the previous examples, we’ll start by launching the Insert Document dialog box and deleting the current text. Next, paste in the following code snippet:
1 2 3 |
{ "_id": 104 } |
At this point, your document should contain only the _id
field, with its value set to 104
. There is a reason we’re taking this approach, which I’ll explain shortly, but first I want to point out something else about the Insert Document dialog box. You might have noticed that, in the upper right corner, there is a View setting that offers two options. The options are shown in the following figure, outlined in red. The first option takes you to as JSON Mode, which is the default view and the one we’ve been working in.
The other option (the right button) takes you to as the Field-by-Field Editor, where you can add fields interactively, as shown in the following figure. Notice that the right option is now selected.
In this case, the _id
field already exists because you defined it in JSON Mode. Had you not taken this approach, Compass would have automatically added the field and assigned a GUID as its value.
MongoDB documentation suggests that you can change the value of the _id
field in the Field-by-Field Editor, but I could not. I tried changing the field’s data type to String
, as the documentation suggested, but that did not help. I also tried changing the data type to Int32
, but that locked up the dialog box and my only option was to cancel out. I tried to find more information about this behavior, but could not. Instead, I was also left with the impression that few people use the Field-by-Field Editor.
Despite this issue, I still want to give you a sense of how to use the Field-by-Field Editor in case you decide to give it a go. As can see in the previous figure, when you point to a field, the Add field option appears (the plus sign to the left of the field name).
To add a field, click the plus sign, and then click the Add field after _id option in the popup menu. This will add a row beneath the _id
field, where you can type a field name and field value. You can also select a data type from the drop-down list at the right of the row.
To define the field, type name for the field name and Darcy for the field value. The String data type will automatically be selected from the drop-down list. Your document should now look like the following figure.
If you had wanted to assign a different data type to the field, you could have selected it from the drop-down list. However, if the value is not permitted for the selected data type, the dialog box will display a message indicating an error. If this occurs, you might have to cancel what you’ve done and start over.
Once you get the hang of how to add fields, you can continue on to the next ones. In this case, you should add the following fields and their values, using the designated data types:
- Field:
location
; value:Portland
; data type:String
- Field:
division
; value:Western
; data type:String
- Field:
current_emp
; value:false
; data type:Boolean
- Field:
yrs_exp
; value:6
; data type:Int32
- Field:
position
; value:Developer
; data type:String
When you’re finished, your document should look like the following figure, as it appears in the Field-by-Field Editor.
I had considered adding an array to this document, but the Field-by-Field Editor does not handle arrays or embedded documents very gracefully. You can create the field itself and assign the Array
or Object
data type to the field, but you cannot add the initial value without switching back to JSON Mode. I opted to wait until after I created the document to add the array, as you’ll see later in the article.
Adding documents based on existing documents
Another method you can use to add a document to a collection is to copy an existing one, paste it into the Insert Document dialog box, and edit it accordingly. After you paste in the document, you can update the individual fields, without worrying about field names or data types. This can be useful if you want to quickly create a document whose schema is similar to the existing one.
For instance, supposed you want to create a document similar to the one with an _id
value of 104
. To copy that document, point to the document in the main Compass window. This will cause a set of icons to appear in the top right corner of the document section, providing options for editing, copying or deleting the document.
Click the Copy to clipboard icon to add the document code to your clipboard. Next, click the Add Data button near the top of the Documents tab, and then click the Insert document option in the popup menu. In the Insert Document dialog box, delete the existing text and paste in the document code from the clipboard. You can then use the following field values to edit the text:
- Field:
_id
; value:105
; data type:Int32
- Field:
name
; value:Carey
; data type:String
- Field:
location
; value:Seattle
; data type:String
- Field:
division
; value:Western
; data type:String
- Field:
current_emp
; value:true
; data type:Boolean
- Field:
yrs_exp
; value:7
; data type:Int32
- Field:
position
; value:SEO Specialist
; data type:String
When you’re finished, your document should look like the one shown in the following code:
1 2 3 4 5 6 7 8 9 |
{ "_id": 105, "name": "Carey", "location": "Seattle", "division": "Western", "current_emp": true, "yrs_exp": 7, "position": "SEO Specialist" } |
Once you’re satisfied with your changes, click the Insert button to add the document to the employees
collection.
In addition to the Copy to clipboard icon, the document section also includes the Clone document icon. This one is handy because, when you click it, Compass automatically launches the Insert Document dialog box and pastes in the document’s code. The only catch is that it does not include the _id
field. You must provide the field yourself, unless you want MongoDB to automatically generate a GUID for that field’s value when the document is added to the collection.
You can test out the cloning feature with the document you just added in the previous example. Point to the document in the main Compass window, and then click the Clone document icon. In the Insert Document dialog box, add the following code snippet above the name
field (including the comma):
1 |
"_id": 106, |
Next, use the following information to update the other field values:
- Field:
name
; value:Avery
; data type:String
- Field:
location
; value:Chicago
; data type:String
- Field:
division
; value:Western
; data type:String
- Field:
current_emp
; value:true
; data type:Boolean
- Field:
yrs_exp
; value:11
; data type:Int32
- Field:
position
; value:Network Admin
; data type:String
When you’re finished, your document should look like the one shown in the following code:
1 2 3 4 5 6 7 8 9 |
{ "_id": 106, "name": "Avery", "location": "Chicago", "division": "Western", "current_emp": true, "yrs_exp": 11, "position": "Network Admin" } |
After you’re done editing the document, click the Insert button to add it to the employees
collection. You should now have six documents in your sample collection—more than enough to demonstrate how to update documents within the Compass GUI.
Updating MongoDB documents individually
The Compass GUI provides two methods for modifying documents in a MongoDB collection: updating the documents individually or updating them in bulk. To update a document individually, you edit the document directly in the interface, which you can do in List View, JSON View, or Table View.
Updating documents in List View
To update an individual document in List View, start by pointing to any field within the document. As you saw earlier, this will cause a set of icons to appear in the upper right corner of the document section, as shown in the following figure.
In this case, the document with an _id
value of 102
is currently selected. To update the document, click the Edit document icon (the pencil). This places the document in editing mode, where you can modify individual field names, field values, or data types. For example, you can change the yrs_exp
value from 14
to 12
, as shown in the following figure.
After you modify the data, click the Update button to save your edits. This will persist your changes to the database.
You can also update a field name in the same way. For instance, you might want to change the name of the yrs_exp
field to years_exp
. Once again, go into editing mode, make your change, and click Update.
Another option for updating a document is to add a field. For instance, suppose you want to add the hire_date
field to the document with an _id
value of 103
. As before, start by putting the document into editing mode. Next, point to the yrs_exp field listing, click the plus sign to the left of the field, and then click the Add field after yrs_exp option in the popup menu.
This will add a row beneath the yrs_exp
field where you can enter the necessary information for the new field:
- For the field name, type hire_date.
- For the field value, type May 13, 2016.
- For the data type, select Date from the drop-down list.
When you’re finished, click Update. The document should now include the hire_date
field.
You can also remove fields from a document. For example, you might decide to delete the current_emp
field. As before, put the document in editing mode. Next, point to the field listing, click the Remove field icon (trash can) to the left of the field name, and then click Update. Your document should now look similar to the following figure.
Notice that the document includes the hire_date
field but no longer includes the current_emp
field. Also notice that the hire_date
field is listed at the end of the document, even though you added it after the yrs_exp
field. MongoDB will typically add new fields to the end of a document when using List View. It will also usually move a field to the end if you change the field name.
Updating documents in JSON View
You can also update documents directly in JSON View, although the process is a little different from List View. You still put the document into editing mode, but you don’t have the types of forms or text boxes you get in the other views. Instead, you work with the code directly, just like you would in a text editor.
For example, you might want to make two changes to the document with an _id
value of 104
. The first change is to update the current_emp
value to true
, and the second change is to add the skills
array to the document.
To make the first change, enter editing mode and modify the text directly, simply changing false
to true
. To make the second change, add a line to the code beneath the yrs_exp
field, and then insert the following field definition (including the comma):
1 |
"skills": [ "Java", "SQL", "Python", "PHP" ], |
Your document should now include both edits, as shown in the following figure, although your changes are not committed to the database as long as you remain in editing mode.
Once you’re satisfied with your updates, click the Replace button. The document should now look similar to this next figure, as it appears in JSON View. In this case, I’ve expanded the skills
array to display all its values.
Notice that the skills
array was not added at the end of the document but rather where you inserted it, after the yrs_exp
field. This is because Compass replaces the document when you’re in JSON View, rather than updating the document, like you saw in List View.
Now let’s modify the document that has an _id
value of 105
. For this document, you’ll delete the yrs_exp
and position
fields and replace them with the following code, which creates the position
embedded document:
1 2 3 4 |
"position": { "title": "SEO Specialist", "dept": "Marketing", "yrs_exp": 7 } |
The position
field includes the yrs_exp
embedded field, which is why you deleted the original field. After you update the code, click Replace. Your document should now look similar to the one in the following figure.
The more comfortable you become with building documents in MongoDB, the greater you’ll appreciate how quickly and easily you can update documents in JSON view, but you must understand how to build a document definition.
Updating documents in Table View
As with List View and JSON View, you can also update documents directly in Table View by putting the document into editing mode, like you’ve been doing. For example, you might decide to add the current_emp
field back into the document with an _id
value of 103
, only this time, setting its value to true
, rather than false
.
To add the field, go into editing mode for that document, click the current_emp
field, and change its value to true
, as shown in the following figure. After you’ve modified the data, click the Update button to save your changes.
In this case, it was particularly easy to add the field to the document because the field already existed in other documents, so there was already a space for it in the Table View grid.
However, if the field you want to add does not exist in other documents, you must specifically add the field to the grid. To do so, click the plus sign associated with one of the fields and then click the Add field after fieldname option in the popup menu, where fieldname is the name of the current field. This will add a column at the right end of the grid, where you can enter the new field information.
Updating MongoDB documents in bulk
You’ll inevitably run into a situation where you’ll want to update multiple documents at the same time. For example, you might be asked to change the division
value in each document in the employees
collection from Western
to North
America
. Currently, the collection contains only six documents, but a collection could easily include thousands of documents.
To update the employees
collection, click the Update button in the main Compass window. In the Update 6 documents dialog box, add the following code snippet to the third line:
1 |
"division": "North America" |
The code indicates that the division
value in each document should be changed to North
America
. After you update the document, the dialog box should look similar to the one shown in the following figure.
Next, click the Update 6 documents button. MongoDB will update the six documents with the new value. However, you will not see your changes until you refresh the main window.
At times, you might need to update only a subset of the documents in the collection. To do a partial update, you must first filter the documents so you end up with a subset that includes only the documents to be modified.
For example, you might want to update the documents with a location
value of Chicago
, changing that value to Minneapolis
. To modify the documents, first create a search filter that returns only the documents with a location
value of Chicago
. This requires that you type or paste the following code snippet into the Filter text box on the query bar:
1 |
{"location": "Chicago"} |
In some cases, the Filter text box will automatically add the curly brackets, depending on how you enter the code. It might also remove duplicate brackets or just leave them. Again, it depends on how you enter the text. No matter what the behavior, however, you should end up with exactly one set of curly brackets surrounding the code.
Once the query is defined, click the Find button to filter the documents. The main Compass window should now display only two documents, each one with a location
value of Chicago
, as shown in the following figure.
After you filter the documents, click the Update button. In the Update 2 documents dialog box, add the following code to the third line:
1 |
"location": "Minneapolis" |
The dialog box should now look similar to the one shown in the following figure. Notice that the filter you defined in the previous step is included in the Filter text box.
Once you’re satisfied with your code, click the Update 2 documents button. MongoDB will update the two documents. However, you’ll need to reset the query filter before you can see your changes. Otherwise, Compass will display only those documents with a location
value of Chicago
, of which there are now none.
Deleting documents in a MongoDB collection
As with updating documents, Compass lets you delete documents individually or in bulk. To delete an individual document, point to the document in List View, JSON View, or Table View. When the document’s set of icons appear, click the Remove document icon (trash can). You’ll then be presented with the option to delete the document.
For example, to remove the document with an _id
value of 104
, point to the document in List View (or one of the other views) and click the Remove document icon. The document will then look like the one in the following figure. Click Delete to remove the document.
In some cases, you might want to delete multiple documents at that same time. For this, you can take the same approach you did when updating documents in bulk. First, create a query that filters out all documents except those you want to delete, and then delete those specific documents.
For example, to delete all documents with a location
value of Minneapolis
, start by entering the following code snippet into the Filter text box in the query bar:
1 |
"location": "Minneapolis" |
After you’ve defined your query, click the Find button to filter the documents. The main Compass window should now display only two documents, each one with a location
value of Minneapolis
.
Next, click the Delete button to launch the Delete 2 documents dialog box, shown in the following figure. Once again, the Filter text box includes the filter you defined in the previous step.
To remove the documents, click the Delete 2 documents button. When Compass prompts you to confirm your deletion, click the Delete 2 documents button again. Be sure to reset the query filter to display the remaining documents.
In some cases, you might want to delete all documents in a collection, which can be especially useful in a development or test environment. For example, to delete the remaining documents in the employees
collection, click the Delete button near the top of the tab to open the Delete 3 documents dialog box, shown in the following figure.
Click the Delete 3 documents button, and then click the button again when prompted to confirm your deletion. Remember to refresh the main document window to verify that all the documents have been removed. The collection should now be empty.
Getting started with the MongoDB Compass GUI
MongoDB Compass makes it fairly painless to add documents to a collection, as well as to update or delete them. You can also work with documents individually or in bulk. The ability to carry out these tasks can be useful for anyone who needs to manipulate content on an ad hoc basis. For example, developers might use Compass to quickly update their test data while trying out features in their applications, or QA personnel might use Compass to add documents to a collection to test certain functionality. Of course, some users will still prefer to use the command line to carry out tasks, but for those who want a quick and easy way to manage their MongoDB documents, Compass can be a good place to start.
Load comments