MongoDB Module 2: CRUD Operations
Introduction
CRUD means create, read, update, and delete, the four operations you do on data every day. MongoDB's versions use JSON-style filters and update operators. This module walks through each with a small product collection.
Prerequisites
- Module 1 completed
- A running MongoDB and mongosh
Step-by-Step Guide
Step 1: Create documents
insertOne adds one document and insertMany adds several. MongoDB adds an _id if you do not provide one. Inserting into a collection that does not exist creates it.
use shop
db.products.insertOne({ sku: "A100", name: "Notebook", price: 4.5, stock: 120, tags: ["paper", "office"] })
db.products.insertMany([
{ sku: "B200", name: "Pen", price: 1.2, stock: 500, tags: ["office"] },
{ sku: "C300", name: "Desk Lamp", price: 24.0, stock: 35, tags: ["home", "light"] },
{ sku: "D400", name: "Backpack", price: 39.9, stock: 0, tags: ["travel"] }
])Step 2: Read documents
find takes a filter and an optional projection that picks which fields to return. Chain sort and limit to order and cap results. findOne returns a single document.
db.products.find()
db.products.find({ price: { $lt: 10 } })
db.products.find({ tags: "office" }, { _id: 0, name: 1, price: 1 })
db.products.find().sort({ price: -1 }).limit(2)
db.products.findOne({ sku: "A100" })
db.products.countDocuments({ stock: { $gt: 0 } })Step 3: Update documents
updateOne and updateMany take a filter and an update document with operators. $set sets fields, $inc adds to a number, $push adds to an array, $unset removes a field. Without an operator, an update document would replace the whole document, so always use operators.
db.products.updateOne({ sku: "A100" }, { $set: { price: 4.75 } })
db.products.updateOne({ sku: "A100" }, { $inc: { stock: -5 } })
db.products.updateOne({ sku: "A100" }, { $push: { tags: "stationery" } })
db.products.updateMany({ tags: "office" }, { $set: { category: "office supplies" } })Step 4: Use upsert and find-and-update
An upsert inserts a new document when nothing matches the filter. findOneAndUpdate changes a document and returns it in one step, which is useful for counters and queues.
db.products.updateOne(
{ sku: "E500" },
{ $set: { name: "Stapler", price: 6.0 }, $setOnInsert: { stock: 10 } },
{ upsert: true }
)
db.products.findOneAndUpdate(
{ sku: "A100" },
{ $inc: { stock: -1 } },
{ returnDocument: "after" }
)Step 5: Delete documents safely
deleteOne removes the first match and deleteMany removes all matches. Run the same filter with find or countDocuments first to see what will be deleted. An empty filter on deleteMany removes everything in the collection.
db.products.countDocuments({ stock: 0 }) // check first
db.products.deleteOne({ sku: "D400" })
db.products.deleteMany({ stock: 0 })FAQs
- Why did my update replace the whole document?
- A replacement happens when the update document has no operators such as $set. In updateOne and updateMany, MongoDB requires operators, but replaceOne and older shell helpers replace the document, so use $set for partial changes.
Summary
Use insertOne and insertMany to create, find with filters and projections to read, update operators such as $set, $inc, and $push to change, and deleteOne or deleteMany to remove, checking the filter before deleting.
Related tutorials
- Databricks Module 8: SQL Warehouses, Performance, Cost, and a First Look at MLflow
- Databricks Module 7: Jobs, Orchestration, and Deploying with Git and Bundles
- Databricks Module 6: Declarative Pipelines and the Medallion Architecture
- Databricks Module 5: Ingesting Files with Auto Loader and COPY INTO
- Databricks Module 4: Unity Catalog, Volumes, and Governance
Comments
Log in or create a free account to join the discussion.