MongoDB Cheat Sheet 🚀

beginner
16 min

MongoDB Cheat Sheet 🚀

Welcome to MongoDB Cheat Sheet, your guide to mastering MongoDB, a versatile, NoSQL database! Let's embark on this exciting journey together. 🎯

Introduction to MongoDB 💡

MongoDB is a popular, open-source, NoSQL database. Unlike traditional SQL databases, MongoDB uses JSON-like documents with optional schemas.

Why MongoDB?

  • Scalable: MongoDB can handle large datasets effortlessly.
  • Flexible: It's perfect for projects that require dynamic and changing data structures.
  • Fast: MongoDB's performance is superior due to its ability to handle complex queries efficiently.

Getting Started 📝

Before diving in, make sure you have MongoDB installed on your machine. Here's a quick link to download MongoDB.

Connecting to MongoDB:

bash
mongo // to connect to the local MongoDB instance

Basic CRUD Operations ✅

Creating a Document (Insert)

Creating a new document is as simple as adding a key-value pair to a collection.

bash
db.collection.insertOne({ key: "value" })

Reading a Document (Find)

To read a document, you can use the find() method followed by the desired fields.

bash
db.collection.find({})

Updating a Document (Update)

Updating a document involves the use of the updateOne() method.

bash
db.collection.updateOne( { _id: <document_id> }, { $set: { key: "new_value" } } )

Deleting a Document (Delete)

Removing a document can be done using the deleteOne() method.

bash
db.collection.deleteOne({ _id: <document_id> })

Advanced MongoDB 💡

Indexing 📝

Indexing is crucial for performance. Here's how to create an index:

bash
db.collection.createIndex({ key: 1 })

Aggregation 💡

Aggregation allows for complex queries and data transformation.

bash
db.collection.aggregate([ { $match: { key: "value" } }, { $group: { _id: "$key", total: { $sum: 1 } } } ])

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What method is used to read a document in MongoDB?

Quick Quiz
Question 1 of 1

How do you create an index in MongoDB?