Introduction
Welcome to the world of MongoDB! If you're new to databases and want to learn how to manage them effectively, you're in the right place. MongoDB is a popular choice for storing and retrieving data in modern applications, and understanding its commands is essential for any developer.
In this beginner-friendly guide, we'll walk through the essential MongoDB commands you need to know. We'll cover three main areas: Databases, Collections, and Documents. By the end of this journey, you'll feel confident navigating and manipulating data in MongoDB like a pro.
Let's dive in and explore the basics of MongoDB together!
Database Commands:
- Creating a Database: MongoDB facilitates database creation using the use command. If the specified database doesn't exist, MongoDB will create it automatically.
use mydatabase
- Viewing Databases: To list all available databases, use the show dbs command. This command displays a list of databases along with their sizes.
show dbs
- Switching Databases: MongoDB allows switching between databases using the use command. This command switches to the specified database.
use dbName
- Viewing Current Database: To view the current database, you can use the db command. This command displays the current database.
db
- Deleting a Database: MongoDB enables dropping databases using the db.dropDatabase() command. Use this command with caution as it permanently removes the specified database and its associated data.
db.dropDatabase()
Collection Commands
-
Creating a Collection:
Collections serve as containers for documents in MongoDB. You can create a collection using the
db.createCollection()
method.
db.createCollection("users")
- Viewing Collections: To list all collections within a database, use the show collections command. This command displays a list of collections in the current database.
show collections
- Dropping a Collection: MongoDB enables dropping collections using the db.collection.drop() method. Exercise caution when dropping collections as it permanently deletes all documents within the collection.
db.users.drop()
Document Commands
- Viewing Documents: MongoDB offers various methods to view documents within a collection. This command retrieves all documents from the "users" collection.
db.users.find()
- View first document: This command just return the first document which is matching the object. ```javascript
db.comments.findOne({name: 'john'})
- **_Prettified Output:_**
MongoDB allows you to view query results in a more readable format using the pretty() method. This command displays all documents in the "users" collection in a neatly formatted manner.
```javascript
db.users.find().pretty()
- Inserting Documents: You can insert documents into a collection using the insertOne() or insertMany() methods.
db.users.insertOne({ name: "John", age: 30 })
- Inserting Many Documents: You can insert multiple documents into a collection simultaneously using the insertMany() method.
db.users.insertMany([
{ 'name': 'John', 'fruit': 'Cherry', 'age': 5 },
{ 'name': 'Alice', 'fruit': 'Banana', 'age': 3 },
{ 'name': 'Suzen', 'fruit': 'Mango', 'age': 4 }
])
- Searching in MongoDB: MongoDB offers flexible querying capabilities. You can search for documents based on specific criteria using the find() method. This command retrieves all documents from the "users" collection where the "age" field is set to "9".
db.users.find({ age: '9' })
- Limiting Output: You can limit the number of documents returned by a query using the limit() method. This command limits the output to the first two documents retrieved from the "users" collection.
db.users.find().limit(2)
- Counting Documents: To count the number of documents returned by a query, you can use the count() method. This command returns the total count of documents in the "users" collection.
db.users.find().count()
- Updating Documents: MongoDB provides the updateOne() method to update a single document that matches the specified criteria. This command updates the age of the first document in the "users" collection where the name is "John" to 35.
db.users.updateOne(
{ name: 'John' },
{ $set: { age: 35 } }
)
- Deleting Documents: Use deleteOne() or deleteMany() methods to delete documents from a collection. This command deletes the first document in the "users" collection where the name is "John".
db.users.deleteOne({ name: "John" })
- Less than Find documents where age is less than 9.
db.users.find({ age: { $lt: 9 } })
- Less than or Equal to: Find documents where age is less than or equal to 9.
db.users.find({ age: { $lte: 9 } })
- Greater than: Find documents where age is greater than 9.
db.users.find({ age: { $gt: 9 } })
- Greater than or Equal to: Find documents where age is greater than or equal to 9.
db.users.find({ age: { $gte: 9 } })
- Additional Operations: MongoDB provides additional operations such as the increment operator and rename operator for advanced document manipulation.
db.users.update({ name: 'John' }, { $inc: { roll_no: 2 } })
This command increments the "roll_no" field by 2 for the document where the name is "John".
db.users.update({ name: 'John' }, { $rename: { roll_no: '10' } })
This command renames the "roll_no" field to "member" for the document where the name is "John".
FunFact😅 My data used to be scattered like socks after laundry day. But then I found MongoDB commands, and now it's all neatly paired up!
Conclusion
Understanding MongoDB commands is really important for managing databases well and building great apps. In this guide, we've learned lots of different commands. We've talked about making databases, managing collections, working with documents, and doing some cool stuff with them. By trying out these commands in your own projects, you'll get really good at using MongoDB and making awesome things. So, keep coding and have fun!
If you liked this blog, please share it with others who might find it useful. You can also keep up with me for more stuff about JavaScript, React, Next.js, MongoDB & Web Development.
You can find me on Twitter, LinkedIn, and GitHub.
Thanks for reading🌻
Top comments (30)
Hi all, there are also other MongoDb commands that can be useful
Indexing Commands:
Creating an Index: db.collection.createIndex({ field: 1 })
Viewing Indexes: db.collection.getIndexes()
Dropping an Index: db.collection.dropIndex("index_name")
Aggregation Commands:
Aggregation Pipeline: db.collection.aggregate([pipeline])
Grouping Documents: $group
Filtering Documents: $match
Projecting Fields: $project
Sorting Documents: $sort
Backup and Restore Commands:
Exporting Data: mongoexport
Importing Data: mongoimport
Database Dump: mongodump
Database Restore: mongorestore
Thanks for sharing!!
Here is a useful one:
db.version()
. This shows the version of the database server you are connected to.Wow, I wasn't aware of this command. Thank you so much for sharing, Prasad!!
Tank you! 👏👏
My pleasuee
Hi Madhu Saini,
Your tips are very useful
Thanks for sharing
Thanks :)
Thanks for that, always good to remember some commands and learn new ones. Great post!
Glad it helped, Thanks for the feedback Lucas
I don't even remember when I last used db commands. I always use mongoose. but nice post though
Hope it refreshed your commands, Thanks Anjan :)
Very useful....and existing information....
Thanks Rohit!
Thank you!
Great to job
Thanks you,. I hope you will soon write a tutorial on connecting mongodb + Nodejs
Gonna write that soon,
Thank you so much for the feedback :)
Some comments have been hidden by the post's author - find out more