Welcome to MongoDB Cheat Sheet, your guide to mastering MongoDB, a versatile, NoSQL database! Let's embark on this exciting journey together. 🎯
MongoDB is a popular, open-source, NoSQL database. Unlike traditional SQL databases, MongoDB uses JSON-like documents with optional schemas.
Why MongoDB?
Before diving in, make sure you have MongoDB installed on your machine. Here's a quick link to download MongoDB.
Connecting to MongoDB:
mongo // to connect to the local MongoDB instanceCreating a new document is as simple as adding a key-value pair to a collection.
db.collection.insertOne({ key: "value" })To read a document, you can use the find() method followed by the desired fields.
db.collection.find({})Updating a document involves the use of the updateOne() method.
db.collection.updateOne(
{ _id: <document_id> },
{ $set: { key: "new_value" } }
)Removing a document can be done using the deleteOne() method.
db.collection.deleteOne({ _id: <document_id> })Indexing is crucial for performance. Here's how to create an index:
db.collection.createIndex({ key: 1 })Aggregation allows for complex queries and data transformation.
db.collection.aggregate([
{ $match: { key: "value" } },
{ $group: { _id: "$key", total: { $sum: 1 } } }
])What method is used to read a document in MongoDB?
How do you create an index in MongoDB?