Video Transcript (English)
At this point, you know how to locate your connection string, connect to your Atlas cluster using the MongoDB Shell, and troubleshoot common connection errors. So now let’s focus more on how to use the MongoDB Shell to interact with your data.
In this video, you’ll learn how to perform specific tasks within the MongoDB Shell, such as: Inserting and retrieving documents, writing and using JavaScript functions, switching between multiple databases within a script, loading scripts into mongosh, and editing commands using your editor of choice.
All of this will help you in upcoming units in this course when we begin to perform operations on our data.
Let’s get started.
Let’s start with a common task: inserting and retrieving documents.
To insert a document, we use the insertOne() command.
And we use the find() command to retrieve a document.
These commands and more will be covered in depth in our units on CRUD operations.
We’ll demonstrate using the sample_mflix database.
Let’s say the movie Christmas Vacation is missing from our database.
First, we’ll verify that the movie doesn’t exist in our database by using the find command.
This command executes a query and returns results.
The argument of the find command is a document containing a field-value pair. In this case, it’s the movie title - the field is title, and the value is Christmas Vacation.
As expected, we don't get any results.
So to fix this, we’ll use the insertOne command. The insertOne command inserts a single document and returns a document containing the status of the insert.
We have only partial information for the movie right now, but that's okay. You'll recall that we can insert documents with different fields within a collection. This means that for now, we can add the information we have, and then update the document as we get more details.
Here we have the full command, with the document as the argument.
This command returns a status that shows the write was acknowledged, and provides the ObjectID for the new document.
Now, we can run the previous find query again and retrieve our document.
As you can see here, the ObjectID returned from the insert matches the ObjectID for the ID field in our document. Nice!
Now that we know how to do simple insert and find operations, let's look at some other useful things you can do with the MongoDB Shell, like use JavaScript functions.
mongosh is built on top of Node.js. This means that with the MongoDB Shell, we can easily leverage the JavaScript programming language.
We’ll start by creating a simple helper function to cube numbers. For this we’ll use our sample_training database.
Our function is called `cube`. It accepts one numeric argument and returns its cube.
We add this function to the global scope of mongosh by pasting the function into mongosh and pressing Enter.
We see that the shell prints out the function name, which indicates that the function was added to the global scope of the shell.
Now let’s run the function. We pass in a value of 16 to the function, run it, and the cube value is returned - 4,096.
This is great - we can add and run JavaScript functions within mongosh. But we don’t want to have to paste in code every time we open a mongosh session. If only we could keep useful JavaScript code that could be loaded when needed.
Luckily, we can!
mongosh has a load() method that allows us to load a JavaScript file into the current shell and run it.
To demonstrate, let’s use a script named “randomPost.js” that prints the body of one random post in a collection of blog posts.
First we switch to the `sample_training` database by using the db.getSiblingDB() method. This method is useful for switching or connecting to databases from our deployment within scripts without providing connection details, which increases the portability of the scripts.
The script performs an aggregation operation on the `posts` collection.
Aggregation operations are processes that allow you to transform and analyze data by applying a sequence of stages, such as filtering, grouping, and sorting to documents in a collection.
The operation here uses the $sample stage to randomly select one document from the collection.
We’ll discuss MongoDB aggregation operations in a later unit.
The query result is stored in the `result` variable. The body of the result - which is the post text - is printed to the console by using mongosh’s built-in print method.
Let’s load the script. We’re connected to our Atlas cluster and currently using the `test` database.
We use the `load` function and pass in the path to our script.
After running the script, a post from the posts collection is printed to the shell.
The prompt now shows that we are using the sample_training database, as a result of the getSiblingDB operation in our script. Nice!
Finally, let's discuss how to use an external editor to edit functions from within mongosh.
If we want to edit how our `cube` function works, we can use the `edit` command to open that function in our editor of choice.
To do this, first we’ll check if we have an editor set by running `config.get('editor')`.
If this returns null, we can set our editor by running config.set(), setting the 'editor' property to our editor of choice. For this example, we’ll use vim, so we’ll run `config.set('editor', 'vim')`.
We run this and see that the editor setting has been changed.
Now that our editor is set, we can edit a function by running `edit` followed by the function.
Let’s edit the `cube` function. We run `edit cube` and the function opens in the vim editor. We change the last line of the script to store the result in a variable, and add a line to return a formatted string containing the starting number and result.
We save and exit the editor.
Back in the shell, we see that the new version of the function appears. We press Enter and the function name prints out, confirming that it has been updated.
When we run the function again, it returns the result in a formatted string.
Using an external editor is helpful when we want to make a change to a multi-line command, or if we want to write a longer command from scratch.
Nice work! Let’s recap.
In this video, you learned how to use the MongoDB Shell to perform specific tasks on your data.
Specifically, you learned how to insert and retrieve a document, and
Write and execute JavaScript code in the MongoDB Shell.
You also learned how to load an external script by using the built-in load() method. We also covered how to use the getSiblingDB() method to change databases and return a random post from a collection.
Finally, you learned how to edit commands in the text editor of your choice. We set a default text editor by using the config.set() command, and then used the `edit` command to edit a function within that editor.
Great job, everyone!
