The Command Line Guide to MongoDB You Wish You Had Earlier
Learn how to manage and query your MongoDB databases directly from the command line, step by step.
Want to get the most out of MongoDB? Learning to use it from the command line gives you hands-on control, making it easier to understand how it works and streamline your workflows.
Playground for command testing
Learning is much easier when you can dive right in and practice every step hands-on. That’s why I’ve created a GitHub repository with a ready-to-use Docker Compose file to get you started in minutes.
https://github.com/the-mzakrzewski/DockerComposeStarter
To get started, you need to clone the repository. Then run this command from the directory:
docker compose -f MongoDB/docker-compose.yml up -dAfter that, you will be able to connect to your container and check what you learned in this article.
Whether you’re new to MongoDB or just want a convenient way to follow along, this setup ensures you have everything you need to practice the commands covered in this tutorial. Let’s get started!
Connecting to MongoDB from the Command Line
This post isn’t focused on using Docker. However, if you’re working with our playground setup, you can connect to the container by running the following command:
docker exec -it mongodb-playground /bin/bashIf you’re unfamiliar with Docker, consider finding a beginner-friendly tutorial to help you get started before continuing with this guide.
In this article, we’ll use the MongoDB Shell (mongosh) to interact with the data in our MongoDB database.
To connect, you’ll need to be on a server (or a container, in our case) where both MongoDB (if you want to use it locally) and the MongoDB Shell are installed. Once you’re there, you can use the following command to connect to the database:
mongosh <connection_string> --username <username>You can omit the connection string if you're connecting to MongoDB locally. In our case, when connecting from inside the container, the command will look like the following:
mongosh --username admin_userOnce you run the connection command, you’ll be prompted to enter the password for the specified user. If you’re using our playground setup, you can find the password in the docker-compose.yml file.
After successfully entering the password, you’ll be connected to your MongoDB instance and ready to start working with it. Let’s begin by creating a database and adding some collections!
Creating Databases and Collections
In MongoDB, data is stored as documents in a format called BSON, which are grouped together into collections. These collections live inside databases, making it easy to organize and manage your data.
The Mongo database stores one or more document collections.
Creating a database in Mongo is very simple; you have to call the use <dbname> command, which switches the database or creates one if it does not exist.
For our example, we are going to create a cinema database in which we will store the data of the movies.
use cinemaThe next step is to create a collection that we are going to use, and we have a couple of ways of doing this. We'll start with the collection creation command db.createCollection(), which is the basic way to do it.
db.createCollection('movies')You can now have a look at what collections are available in our database:
db.getCollectionNames()Knowing that our collection was created, we'll drop it and see in the next chapter how to create collections during insertion.
db.movies.drop()Adding Documents to a Collection
We need to populate our collection with some data (BSON documents in the case of MongoDb) before we can check other commands on it. You can add one at a time (db.collection.insertOne()) or many at a time (db.collection.insertMany()).
And this is also a second way of creating a collection. By calling one of the insert functions, the collection is created if it does not exist.
Let’s begin with a simple insert to demonstrate how MongoDB documents resemble JSON objects. If you’re curious about the differences between JSON and BSON, take a look at this resource: Explaining BSON.
db.movies.insertOne({
title: "Inception",
director: "Christopher Nolan",
release_year: 2010,
genres: [ "Sci-Fi", "Action", "Thriller" ],
rating: 8.8
})Once this operation has been completed, the first film will be added to our collection. Now we can use batch insert to add a few more to the collection.
db.movies.insertMany([
{
title: "The Shawshank Redemption",
director: "Frank Darabont",
release_year: 1994,
genres: ["Drama", "Crime"],
rating: 9.3
},
{
title: "The Dark Knight",
director: "Christopher Nolan",
release_year: 2008,
genres: ["Action", "Crime", "Drama"],
rating: 9.0
}
])There should be 3 movies in our collection by now. You can check this by calling db.collection.find() command on the collection.
We will learn more about this command in the next chapter; for now, we will call it without any parameters.
db.movies.find()Retrieving Data from a Collection
It’s time to retrieve the data using the db.collection.find() command. This is one of the most commonly used commands in MongoDB and allows you to query your collection for specific documents or view all the documents stored in it.
You can use this command without any parameters, as we've done after adding some films to our collection, to get all of the documents. However, as in SQL, this command is most useful when we start to use a number of filters.
Let's start by specifying basic conditions, where we use a list of fields and the value we're looking for:
{ <field1>: <value1>, ... }
db.movies.find({
title: 'The Dark Knight'
})
db.movies.find({
director: 'Christopher Nolan',
release_year: 2010
})The equivalent of these queries in SQL are
SELECT * FROM movies WHERE title = 'The Dark Knight';
SELECT * FROM movies WHERE director = 'Christopher Nolan' AND release_year = 2010;But there is another way to set conditions for filter functions with query operators; the syntax is similar, but instead of specifying the value, we also have to specify the operator:
{ <field1>: { <operator1>: <value1> }, ... }
Assume that we want to find movies with a release year greater than 2008.
db.movies.find({
release_year: {$gt: 2008}
})The '$gt' operator is a query operator that tells us that we are looking for values that are greater than a given value.
There are many operators you can use to find the data you're looking for. The full list can be found here, in the MongoDB documentation.
Of course, you can also combine the two types of filters in a single find command:
db.movies.find({
director: 'Christopher Nolan',
release_year: {$gt: 2008}
})Updating Documents in a Collection
Updating documents in MongoDB is a broad topic, so in this article I will only show how to update the values of an existing document using the $set operator. However, I encourage you to find out what other options Mongo has for updating documents (other operators).
There are 3 functions we can use to update documents:
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
Both update functions will update selected field values; the difference between updateOne() and updateMany() is that the first one will only update the first document that can be found for the given criteria.
While the replaceOne() function will overwrite the entire document.
For example, say you want to update all Nolan movie ratings to 10. As the first argument of the function, you have to pass a criteria, the format of which is the same as that of the filter function from the previous chapter. The second argument is an object of update operators; in our example, we only use $set, which updates the passed field's value.
{ <update operator>: { <field1>: <value1>, ... }, ... }
db.movies.updateMany(
{ director: 'Christopher Nolan' },
{
$set: { rating: 10 }
}
)Let's use replaceOne() to find all movies with a rating less than 10 and replace the whole document:
db.movies.replaceOne(
{ rating: { $lt: 10 } },
{
title: 'Better not to watch'
}
)As you can see, we only set one value for the record. Because of the way MongoDB works, each document can have a different structure.
Cleaning Up a Collection
If you want to remove documents from collection, you need to use one of the two methods that we have: db.collection.deleteOne() or db.collection.deleteMany().
For both of these methods, we have to specify the criteria that the document has to pass in order to be deleted. The difference is that in the case of db.collection.deleteOne(), only the first document that is a match for the criteria will be deleted.
The criteria are passed on in the same way as we have done it when we retrieved the data.
db.movies.deleteOne({
release_year: {$gt: 2008}
})
db.movies.deleteMany({
director: 'Christopher Nolan'
})Summary
In this article, I’ve covered just the basics of what you can do with MongoDB. Topics like indexing, aggregation operations, and transactions offer even more powerful capabilities to explore. However, the main goal here was to help you get comfortable with the core commands for the MongoDB CLI. I hope this guide has boosted your confidence in working with it!
I encourage you to use the playground from the first chapter to practice what you’ve learned; hands-on experience is the best way to make it stick.
If you’re eager to dive deeper into MongoDB’s features, check out the official documentation, which served as the primary source for this article.
Happy coding!


