23 MongoDB Commands and Queries Every Developer and DBA Should Know
Let’s talk about some of the frequently used MongoDB queries and commands that every developer and DBA should know. Don’t worry, we won’t bore you with complex syntax and technical jargon. We plan to keep things light-hearted and casual, explaining each concept like you’re a 5-year-old.
What’s MongoDB?
MongoDB is a cross-platform, document-oriented, open-source NoSQL database used to store semi-structured data written in C++.
It’s like a virtual file cabinet where you can store your data without having to worry about organizing it into neat little tables and columns.
Instead of storing data in tables, MongoDB stores it in key-value pairs called documents. For example, imagine you have a “fruits” collection in your MongoDB database.
Here’s a Video You want to Watch to Install MongoDb On Windows:
https://www.youtube.com/watch?v=gB6WLkSrtJk
Your data could be organized like this:
{
“name”: “Apple”,
“color”: “Red”,
“taste”: “Sweet”
}
{
“name”: “Banana”,
“color”: “Yellow”,
“taste”: [“Sweet,” “Sour”]
}
As you can see, each document represents a piece of data, and you can have different types of data in the same collection without any rigid structure.
23 Fun MongoDB Commands and Queries
Alright, enough with the basics. Let’s dive into some fun MongoDB commands and queries.
Basic Commands
#1. Check Your MongoDB Version
You can start by clearing your shell. Click ‘Ctrl + ‘L’ on Windows or ‘Command + K’ for Mac. This command will clear your shell and give you a fresh start.
To check the version of MongoDB you’re running, run the following command:
db.version()
Result:
test> db.version()
7.0.2
test>
#2. Listing MongoDB Commands
You can use this command to get a list of all the commands available in MongoDB:
help()
Result:
Shell Help:
use Set current database
show ‘show databases’/’ show dbs’: Print a list of all available databases.
‘show collections’/’ show tables’: Print a list of all collections for current database.
‘show profile’: Prints system.profile information.
‘show users’: Print a list of all users for current database.
‘show roles’: Print a list of all roles for current database.
‘show log <type>’: log for current connection, if type is not set uses’ global’
‘show logs’: Print all logs.
#3. DB Statistics
The db.stats() command can be used to check the statistics of your current database. That includes the size of the database, number of collections and indexes, storage size, etc.
Command
db.stats()
Result:
{
“db”: “test”,
“collections”: 5,
“views”: 0,
“objects”: 7,
#4. Listing all Databases
This command will list all the databases you’ve created. It will include all system databases as well.
show dbs
Result:
test> show dbs
AnimalDB 40.00 KiB
admin 40.00 KiB
config 108.00 KiB
local 40.00 KiB
test>
#5. Create New Database
You can create a new database right from the MongoDB shell by using this command. You don’t need to create a database file from your MongoDB GUI manually.
You can also use this command to switch to a different database by specifying its name.
If the specified database already exists, then MongoDB will switch to that database.
Syntax:
use <database_name>
For example, let’s create a database called MediaOne.
Here’s the command to run:
use MediaOne
Result
switched to db MediaOne
MediaOne>
#6. See the Database You’re Currently Using
To see the current database you’re using, you can use the db command. The command will print out the name of your current database.
Example:
db
Result:
MediaOne>
#7. Drop a Database
If you want to delete a database, you can use the db.dropDatabase() command. This will permanently delete the specified database from your MongoDB server.
Here’s how you can use this command:
First, you have to switch to the database you want to drop. Use the ‘use’ command for this.
For example, let’s say we want to delete the AnimalDB database:
You’ll first have to run:
use AnimalDB
Then, use the db.dropDatabase() command:
db.dropDatabase()
This will delete the AnimalDB database from your server. Note that this action cannot be undone, so make sure you are certain before executing this command.
Switch to the database you want to delete
use AnimalDB
Result
switched to db AnimalDB
Delete the Database
db.dropDatabase()
Result
{ ok: 1, dropped: ‘AnimalDB’}
Confirm Deletion
AnimalDB> show dbs
Result
admin 40.00 KiB
config 108.00 KiB
local 40.00 KiB
The AnimalDB database is missing from the list of databases shown.
#8. Create a Collection
A collection is like a table in traditional databases. Remember, a database can have as many collections as you want.
For example, say you want to create a “Books database.” You can have a collection for “Fiction”, “Non-Fiction”, and “Biographies” within this database.
It’s like a subcategory of your main database.
That’s why, in MongoDB, you only need one database and as many collections as possible to keep things organized.
To create a collection in MongoDB, you can use the db.createCollection() command. Here’s how it works:
Syntax:
db.createCollection( collection-name, options )
Example:
db.createCollection( “Fiction” )
This will create a collection named Fiction within the Books database.
However, you want to switch to the database in which you want to create the collection first using the ‘use’ command we mentioned earlier.
Here’s an example of the flow.
Let’s say we want to create a collection for ‘readers’ in our MediaOne database.
Step 1:
use MediaOne
Results
switched to db MediaOne
Step 2:
db.createCollection(“Readers”)
Results:
MediaOne> db. createCollection(“Readers”)
{ ok: 1 }
That will create a collection named ‘readers’ within the MediaOne database.
Note: You want to make sure the collection you’re creating is covered in quotes. Otherwise, you’ll receive the undefined error.
You can also create a capped collection in MongoDB, a fixed-size collection that automatically overwrites older data when it reaches its maximum size. To create a capped collection, you will need to add an extra option parameter with the desired options.
Here’s how it works:
Syntax:
db.createCollection(name, {capped: boolean, size: number, max: number(document limit)})
Example:
db.createCollection(“Fiction,” { capped: true, size: 5120000, max: 5000 })
That will create a capped collection named “Fiction” with a maximum size of 5 megabytes and a document limit of 5000 within the Books database.
Creating collections in MongoDB allows you to organize your data efficiently and effectively. It also allows you to customize your collections based on your specific needs, such as creating capped collections for time-sensitive data or using different storage engines for specific data types. With these capabilities, MongoDB provides developers and DBAs with powerful tools to manage and manipulate data in their databases.
#9. Drop a Collection
Just as you can create a collection in MongoDB, you can also drop or delete a collection when it is no longer needed.
The command will delete the specified collection together with all of its data.
It returns true if the command executes successfully and false otherwise.
Syntax:
db.CollectionName.drop()
Example:
db.Fiction.drop()
This will delete the “Fiction” collection from the Books database.
Example:
Books> use MediaOne
switched to db MediaOne
MediaOne> db.users.drop()
true
MediaOne>
#10. Show Collection Names
To get a list of all the collections in your database, you can use the command “show collections.” This will return a list of all collection names in your current database.
Syntax:
show collections
Example:
MediaOne> show collections
Results:
Reader
Users
#11 See the Data in a Collection
To view all the data stored within a collection, use the command “db.CollectionName.find()”. This will return all documents in the specified collection. You can also specify parameters to filter and sort the data returned.
Syntax:
db.CollectionName.find()
Example:
db.Reader.find()
This will return all documents in the “Reader” collection.
Example:
MediaOne> db.Reader.find()
Results
[
{
_id: ObjectId(“651e78ea4ab05fa01323287d”),
name: ‘Grace Gui’,
age: 21
}
]
CRUD in MongoDB
CRUD stands for Create, Read, Update, and Delete. These are the basic operations devs and DBA perform on data in a database. MongoDB provides several commands to perform these operations.
#12. Create Documents
Similar to tuples or rows in traditional databases, MongoDB stores data in documents. To create a document, you can use the insert() method.
You just have to specify if you’re going to insert one or many documents.
If it’s one, you can use the insertOne() method.
If it’s many, you can use the insertMany() method.
Syntax:
db.CollectionName.insert({ key: “value” })
Example:
db.Fiction.insertOne({ title: “Gone Girl”, author: “Gillian Flynn”, genre: “Thriller”})
This will create a new document with the specified fields and values in the “Fiction” collection.
MediaOne> use Books
switched to db Books
Books> db.Fiction.insertOne({title: “Gone Girl”, author: “Gillian Flynn”, genre: “Thriller”})
{
acknowledged: true,
insertedId: ObjectId(“651e7c675f5888e0a3d30aea”)
}
Insert Many Documents
You can use the insertMany() method to insert multiple documents at once.
Syntax:
db.CollectionName.insertMany([{ key1: “value1” }, { key2: “value2” }, …])
Example:
db.Fiction.insertMany([{ title: “The Silent Patient”, author: “Alex Michaelides”, genre: “Thriller”}, { title: “The Girl on the Train”, author: “Paula Hawkins”, genre: “Mystery”}])
This will insert two new documents in the “Fiction” collection with the specified fields and values.
Results:
{
acknowledged: true,
insertedIds: {
‘0’: ObjectId(“651e7d295f5888e0a3d30aeb”),
‘1’: ObjectId(“651e7d295f5888e0a3d30aec”)
}
}
Remember, this is the code you’ll need to use when working with any backend development tool, including .NET or Java.
For example, if you’re using express.js, here’s how the code looks like:
app.post(“/fiction”, async (req, res) => {
const newFiction = await req.body. //Getting the new fiction object from the request body
db.collection(‘ Fiction’).insertOne(newFiction) //Inserting the new fiction object into the “Fiction” collection
.then(result => {
res.send(“Successfully inserted a new document.”);
})
.catch(err => console.log(err));
});
This is an example of how you can use MongoDB commands in your backend code to perform CRUD operations on your database. It’s a similar process for other development tools as well. The only difference here is that we mention the word collection and then put the collection name in a bracket in quotes.
#13. Read or Retrieve
The second most common operation in MongoDB is reading or retrieving data from a database. This is done using the find() method.
We’ve already covered this, but there’s no harm in revisiting it again. The find() method takes in a query object as its parameter and returns the matching documents from the collection.
Syntax:
db.CollectionName.find()
This will return the entire collection, including all the documents.
To filter or narrow down your results, you can pass in a query object as a parameter to the find() method. This will return only those documents that match the specified conditions.
Syntax:
db.CollectionName.find({ key: value})
For example, if we want to retrieve all books from the “Fiction” collection where the genre is “fantasy,” we can use this query:
db.Fiction.find({genre: “Mystery”})
This will return all the documents in the “Fiction” collection that have the genre value set to “fantasy.”
Books> db.Fiction.find({genre: “Mystery”})
[
{
_id: ObjectId(“651e7d295f5888e0a3d30aec”),
title: ‘The Girl on the Train’,
author: ‘Paula Hawkins’,
genre: ‘Mystery’
}
]
#14. Beautify the Retrieved Output
It’s always good to have a clean and organized output when retrieving data from a database. To achieve this, we can use the pretty() method after the find() method.
Syntax:
db.CollectionName.find().pretty()
This will format the output in an easy-to-read and well-structured manner.
#15. Update Multiple Documents
You can also update multiple documents in a collection using the update() method.
Syntax:
db.CollectionName.updateOne({ key: value }, { $set: { newKey: newValue } })
db.CollectionName.updateMany({ key: value }, { $set: { newKey: newValue } })
The first method, updateOne(), will update the first document that matches the specified condition.
The second method, updateMany(), will update all documents that match the specified condition.
For example, if we want to update the “author” field for all documents that have the genre value set to “Thriller,” we can use this query:
db.Fiction.updateMany({ genre: “Thriller” }, { $set: { author: “John Smith” } })
This will set the author value to “John Smith” for all Thriller books in the Fiction collection.
Or, if we wish to add a new field to all documents that have a certain field, we can use the $set operator to do so:
For example, to add pricing to all books in the Thriller genre, we can use this query:
db.Fiction.updateMany({ genre: “Thriller” }, { $set: { pricing: “10.99 USD” } })
This will add a new field called “pricing” with the value of “10.99 USD” to all Fiction collection documents with a genre value of Thriller.
Books> db.Fiction.updateMany({ genre: “Thriller” }, { $set: { pricing: “10.99 USD” } })
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
The update() method can modify, upsert (create if not existing), or replace the document that matches the specified condition. By default, it will modify the first matching document.
#16. Delete Documents
Onto the last part of CRUD – deleting documents. Similar to updating, there are two methods for deleting documents in MongoDB: deleteOne() and deleteMany().
Syntax:
db.CollectionName.deleteOne({ key: value })
db.CollectionName.deleteMany({ key: value })
The first method, deleteOne(), will delete the first document that matches the specified condition. The second method, deleteMany(), will delete all documents that match the specified condition.
For example, if we want to delete a book from the Fiction collection with the title “Gone Girl,” we can use this query:
db.Fiction.deleteOne({ title: “Gone Girl” })
Result
Books> db.Fiction.deleteOne({ title: “Gone Girl” })
{ acknowledged: true, deletedCount: 1 }
This will delete the first document with the title “Gone Girl” in the Fiction collection.
Or, if we want to delete all books from the Fiction collection with a genre value of “Romance,” we can use this query:
db.Fiction.deleteMany({ genre: “Romance” })
This will delete all documents in the Fiction collection that have a genre value of “Romance.”
#17. Removing an Item from a Subdocument
And how do we remove an item from a subdocument? We can use the $pull operator, which removes all array elements that match a specified condition. Here’s an example:
Let’s say we have a Fiction collection with the following document:
{
_id: ObjectId(“5f8c33594678164eff7cffbe”),
title: “Harry Potter and The Goblet of Fire”,
genre: “Fantasy”,
authors: [
{
name: “J.K. Rowling”,
age: 55
},
{
name: “John Doe”,
age: 40
}
]
}
If we want to remove the author with the name “John Doe,” we can use this query:
db.Fiction.updateOne({ title: “Harry Potter and The Goblet of Fire” }, { $pull: { authors: { name: “John Doe” }}})
This will remove the entire subdocument that matches the condition, in this case, the author with the name “John Doe.” The updated document will look like this:
{
_id: ObjectId(“5f8c33594678164eff7cffbe”),
title: “Harry Potter and The Goblet of Fire”,
genre: “Fantasy”,
authors: [
{
name: “J.K. Rowling”,
age: 55
}
]
}
MongoDB Commands
#18. Delete a Document in a Collection Based on a Condition
We can use the deleteOne() or deleteMany() commands to delete a document in a collection based on a specific condition. Here’s an example:
Let’s say we have a Fiction collection with the following documents:
{
title: “Harry Potter and The Goblet of Fire”,
genre: “Fantasy”
},
{
title: “The Hunger Games”,
genre: “Sci-Fi”
}
If we want to delete the document with a title of “The Hunger Games,” we can use this query:
Books> db.Fiction.deleteOne({ title: “The Hunger Games” })
{ acknowledged: true, deletedCount: 1 }
Books>
This will delete the “The Hunger Games” document from the collection. However, if you want to delete multiple documents that match a given condition, you can use the deleteMany() command.
For example:
db.Fiction.deleteMany({ genre: “Sci-Fi” })
That will delete all documents in the Fiction collection with a genre of “Sci-Fi.” Just make sure to use the appropriate command depending on your needs.
#19. Retrieve Distinct Field Values from a Collection
Sometimes, we may need to retrieve only distinct records from a specific field in a collection. We can use the distinct() command to return an array of distinct values for a given field.
Here’s an example:
Let’s say our Fiction collection now has multiple documents with the same genre value like this:
([{
title: “Harry Potter and The Goblet of Fire”,
genre: “Fantasy”
},
{
title: “The Hunger Games”,
genre: “Sci-Fi”
},
{
title: “Percy Jackson and The Lightning Thief”,
genre: “Fantasy”
}])
If we want to retrieve only the distinct values of genre from our collection, we can use this query:
db.Fiction.distinct(“genre”)
That will return an array with the values “Fantasy” and “Sci-Fi” as our collection’s only two distinct genres. That can be useful when we want to get a quick overview of the different categories or types of data present in our collection.
However, remember that this command may not be efficient for large collections as it will have to scan through all the documents. You might want to use indexes and other advanced techniques for better performance in such cases.
#20. Rename a Collection
Sometimes, we may need to change the name of a collection for better organization or other reasons. For this, we can use the renameCollection() command.
Here’s the syntax for renaming a collection:
db.collection.renameCollection( newName)
The first parameter specifies the new name for our collection, and the second parameter is optional and specifies whether to drop the target collection if it already exists.
For example, let’s say we want to rename our Fiction collection to Novels. We can use this command:
db.Fiction.renameCollection(“Novels”)
That will change the name of our collection from Fiction to Novels. Remember that this command will not affect the documents within the collection, only its name.
#21. Creating an Index
Indexes are data structures that help improve the performance of our queries by allowing faster access to data. They are especially useful for collections with a large number of documents.
MongoDB provides the default _id index for all collections, which is automatically created and maintained. However, we can also create custom indexes using the createIndex() command.
Here’s the syntax for creating an index:
db.collection.createIndex( keys, options)
The first parameter specifies the fields to be indexed, and the second parameter is optional and contains additional options, such as specifying if the index should be unique or sparse.
For example, let’s say we want to create an index on our Fiction collection for its title field. We can use this command:
db.Fiction.createIndex({key: 1})
By default, this will create an index on the title field in ascending order (1).
#22. Show Index on Document
After creating an index on a collection, we can use the getIndexes() command to see all the indexes applied to that collection.
For example, if we want to see all the indexes applied to our Novels collection, we can use this command:
db.Novels Books> db.Novels.getIndexes()
[ { v: 2, key: { _id: 1 }, name: ‘_id_’ } ]ls.getIndexes()
That will return a list of all the indexes applied to our Novels collection, including the _id index and any custom indexes we have created.
#23. Remove an Index from a Collection
If we no longer need an index on a collection, we can use the dropIndex() command to remove it.
For example, if we want to remove the index on the title field in our Fiction collection, we can use this command:
db.Fiction.dropIndex(“title_1”)
Books> db.Fiction.dropIndex(“title_1”)
{ nIndexesWas: 3, ok: 1 }
This will remove the index with the name “title_1” from our Fiction collection.
MongoDB Commands