All MongoDB commands you need to know

Madhu Saini - Apr 5 - - Dev Community

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🌻

. . . . . . . . . .