DEV Community

Cover image for All MongoDB commands you need to know
Madhu Saini
Madhu Saini

Posted on

All MongoDB commands you need to know

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


Enter fullscreen mode Exit fullscreen mode
  • 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


Enter fullscreen mode Exit fullscreen mode
  • Switching Databases: MongoDB allows switching between databases using the use command. This command switches to the specified database.


use dbName


Enter fullscreen mode Exit fullscreen mode
  • Viewing Current Database: To view the current database, you can use the db command. This command displays the current database.


db


Enter fullscreen mode Exit fullscreen mode
  • 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()


Enter fullscreen mode Exit fullscreen mode

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")


Enter fullscreen mode Exit fullscreen mode
  • 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


Enter fullscreen mode Exit fullscreen mode
  • 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()


Enter fullscreen mode Exit fullscreen mode

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()


Enter fullscreen mode Exit fullscreen mode
  • 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()


Enter fullscreen mode Exit fullscreen mode
  • Inserting Documents: You can insert documents into a collection using the insertOne() or insertMany() methods.


db.users.insertOne({ name: "John", age: 30 })


Enter fullscreen mode Exit fullscreen mode
  • 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 }
])


Enter fullscreen mode Exit fullscreen mode
  • 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' })


Enter fullscreen mode Exit fullscreen mode
  • 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)


Enter fullscreen mode Exit fullscreen mode
  • 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()


Enter fullscreen mode Exit fullscreen mode
  • 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 } }
)


Enter fullscreen mode Exit fullscreen mode
  • 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" })


Enter fullscreen mode Exit fullscreen mode
  • Less than Find documents where age is less than 9.


db.users.find({ age: { $lt: 9 } })


Enter fullscreen mode Exit fullscreen mode
  • Less than or Equal to: Find documents where age is less than or equal to 9.


db.users.find({ age: { $lte: 9 } })


Enter fullscreen mode Exit fullscreen mode
  • Greater than: Find documents where age is greater than 9.


db.users.find({ age: { $gt: 9 } })


Enter fullscreen mode Exit fullscreen mode
  • Greater than or Equal to: Find documents where age is greater than or equal to 9.


db.users.find({ age: { $gte: 9 } })


Enter fullscreen mode Exit fullscreen mode
  • 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 } })


Enter fullscreen mode Exit fullscreen mode

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' } })


Enter fullscreen mode Exit fullscreen mode

This command renames the "roll_no" field to "member" for the document where the name is "John".

Image

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)

Collapse
 
gorhovakimyan profile image
gorhovakimyan2001

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

Collapse
 
madhusaini22 profile image
Madhu Saini

Thanks for sharing!!

Collapse
 
prsaya profile image
Prasad Saya

Here is a useful one: db.version(). This shows the version of the database server you are connected to.

Collapse
 
madhusaini22 profile image
Madhu Saini

Wow, I wasn't aware of this command. Thank you so much for sharing, Prasad!!

Collapse
 
pavelee profile image
Paweł Ciosek

Tank you! 👏👏

Collapse
 
madhusaini22 profile image
Madhu Saini

My pleasuee

Collapse
 
jangelodev profile image
João Angelo

Hi Madhu Saini,
Your tips are very useful
Thanks for sharing

Collapse
 
madhusaini22 profile image
Madhu Saini

Thanks :)

Collapse
 
lucaschitolina profile image
Lucas Chitolina

Thanks for that, always good to remember some commands and learn new ones. Great post!

Collapse
 
madhusaini22 profile image
Madhu Saini

Glad it helped, Thanks for the feedback Lucas

Collapse
 
thatanjan profile image
Anjan Shomodder

I don't even remember when I last used db commands. I always use mongoose. but nice post though

Collapse
 
madhusaini22 profile image
Madhu Saini

Hope it refreshed your commands, Thanks Anjan :)

Collapse
 
rohiitbagal profile image
Rohit

Very useful....and existing information....

Collapse
 
madhusaini22 profile image
Madhu Saini

Thanks Rohit!

Collapse
 
jonnydev profile image
Jonathan

Thank you!

Collapse
 
cheikhnouha profile image
Cheikhnouha

Great to job

Collapse
 
skipperhoa profile image
Hòa Nguyễn Coder

Thanks you,. I hope you will soon write a tutorial on connecting mongodb + Nodejs

Collapse
 
madhusaini22 profile image
Madhu Saini

Gonna write that soon,

Thank you so much for the feedback :)

Some comments have been hidden by the post's author - find out more