All MongoDB commands you need to know
Tags: mongodb, webdev, backend, database
Published: 2024-04-05 14:56:37

## 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.

```javascript
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.

```javascript
show dbs
```

- _**Switching Databases:**_
MongoDB allows switching between databases using the use command. This command switches to the specified database.

```javascript
use dbName
```

- _**Viewing Current Database:**_
To view the current database, you can use the db command. This command displays the current database.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

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

- **_Inserting Many Documents:_**
You can insert multiple documents into a collection simultaneously using the insertMany() method.

```javascript
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".

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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".

```javascript
db.users.deleteOne({ name: "John" })
```

- **_Less than_**
Find documents where age is less than 9.

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

- **_Less than or Equal to:_**
Find documents where age is less than or equal to 9.

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

- **_Greater than:_**
Find documents where age is greater than 9.

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

- **_Greater than or Equal to:_**
Find documents where age is greater than or equal to 9.

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



- _**Additional Operations:**_
MongoDB provides additional operations such as the increment operator and rename operator for advanced document manipulation.

```javascript
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".

```javascript
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".


![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ex9r8w2hqgbk9e40p32p.gif)

> 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](https://twitter.com/MadhuSaini22), [LinkedIn](https://www.linkedin.com/in/madhu-saini/), and [GitHub](https://github.com/MadhuSaini22).

Thanks for reading🌻