CRUD Operations in MongoDB

This section dives into CRUD operations, the foundation of interacting with your MongoDB database. We’ll explore how to Create, Read, Update, and Delete documents, giving you the power to manage your data effectively. Get ready to add, retrieve, modify, and remove information with ease!

Connect to MongoDB

mongo

Open a terminal and start the MongoDB shell by typing mongo.

Create and Use a Database

use blog

Create (if not exists) and use the ‘blog’ database

Create Collections

// Create a 'posts' collection
db.createCollection("posts")

// Create a 'users' collection
db.createCollection("users")

Create two collections: posts for storing blog posts and users for storing user information.

Insert Operations

Insert a single document into ‘posts’ collection


db.posts.insertOne({
title: "Introduction to MongoDB",
content: "MongoDB is a NoSQL database.",
author: "John Doe",
tags: ["mongodb", "nosql", "database"]
})

Insert multiple documents into ‘users’ collection

db.users.insertMany([
{
username: "johndoe",
email: "johndoe@example.com",
age: 30
},
{
username: "janedoe",
email: "janedoe@example.com",
age: 28
}
])

Update Operations

Update a document in ‘users’ collection

db.users.updateOne(
{ username: "johndoe" },
{ $set: { age: 31 } }
)

Update multiple documents in ‘posts’ collection

db.posts.updateMany(
{ tags: "mongodb" },
{ $addToSet: { tags: "database" } }
)

Delete Operations

Delete a document from ‘users’ collection

db.users.deleteOne({ username: "janedoe" })

Delete multiple documents from ‘posts’ collection

db.posts.deleteMany({ author: "John Doe" })

Drop the entire ‘users’ collection

db.users.drop()

Query Operations

Find all documents in ‘posts’ collection

db.posts.find()

Find one document in ‘posts’ collection

db.posts.findOne({ title: "Introduction to MongoDB" })

Find and modify a document in ‘posts’ collection

db.posts.findOneAndUpdate(
{ title: "Introduction to MongoDB" },
{ $set: { content: "MongoDB is a flexible and scalable NoSQL database." } }
)

Find one and delete a document in ‘posts’ collection

db.posts.findOneAndDelete({ author: "John Doe" })

Find one and replace a document in ‘posts’ collection

db.posts.findOneAndReplace(
{ title: "Introduction to MongoDB" },
{ title: "MongoDB Overview", content: "A detailed guide to MongoDB." }
)

Query with Projections

Find documents with projection (only return ‘title’ and ‘author’ fields)

db.posts.find({}, { title: 1, author: 1 })

Query nested documents (e.g., find users with email ending in ‘.com’)

db.users.find({ "email": /.*\.com$/ })

Query documents with null or missing fields

db.users.find({ email: null })

Show Database Information

// Show available databases
show dbs

// Show collections in the current database
show collections

To see a list of available databases and their collections

MongoDB Cheat Sheet

MongoDB is a document-oriented NoSQL database that revolutionizes data storage with its flexibility and scalability. By storing data in JSON-like documents, MongoDB offers developers a powerful and intuitive way to handle complex data structures. From basic CRUD operations to advanced aggregation techniques, MongoDB empowers users to build robust and dynamic applications with ease.

In this MongoDB cheat sheet, we’ll delve into MongoDB’s key concepts, including data types, CRUD operations, query techniques, aggregation framework, indexing strategies, transaction support, and data modeling approaches. Each section is packed with examples and explanations to help you grasp MongoDB’s functionalities quickly and efficiently.

Similar Reads

MongoDB Basics

...

CRUD Operations in MongoDB

This section dives into CRUD operations, the foundation of interacting with your MongoDB database. We’ll explore how to Create, Read, Update, and Delete documents, giving you the power to manage your data effectively. Get ready to add, retrieve, modify, and remove information with ease!...

MongoDB Operators

MongoDB operators are special symbols or keywords that unlock the power of your data. Just like a chef uses tools to prepare a meal, these operators help you find, modify, and analyze information stored in your MongoDB database. Mastering these operators empowers you to efficiently query, manipulate, and unlock the hidden insights within your data....

MongoDB Aggregation Framework

We’ll perform various aggregation operations using MongoDB’s aggregation framework...

MongoDB Indexing

Indexing enhances query performance and allows for efficient data retrieval in MongoDB...

Transactions in MongoDB

MongoDB supports multi-document ACID transactions, allowing for atomicity, consistency, isolation, and durability....

Data Modeling in MongoDB

Data modeling in MongoDB involves designing schemas and relationships between documents....

Conclusion

MongoDB stands out as a versatile and powerful document-oriented NoSQL database, offering developers a flexible and scalable solution for handling complex data structures. Throughout this cheat sheet, we’ve explored MongoDB’s key concepts, from its fundamental data types to advanced features such as CRUD operations, querying techniques, aggregation framework, indexing strategies, transaction support, and data modeling approaches....