Welcome to MongoDB! MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. Instead of tables and rows like in SQL, you have collections which contain documents. These documents are stored in a binary-encoded format called BSON (Binary JSON).
Let's dive into the four fundamental operations you'll perform on this data: Create, Read, Update, and Delete (CRUD).
Part 1: Using the Interactive Mongo Shell
The mongosh shell is a powerful command-line tool for interacting directly with your database. It's perfect for testing, debugging, and administrative tasks.
First, connect to your database by typing mongosh in your terminal.
Bash
# To switch to a database (it will be created if it doesn't exist) > use myNewStore # To see the current database > db
Create: Inserting Documents
We use insertOne() to add a single document and insertMany() to add multiple.
JavaScript
// Insert a single product into the 'products' collection
> db.products.insertOne({ name: "Laptop", price: 1200, inStock: true })
// Insert multiple products at once
> db.products.insertMany([
{ name: "Mouse", price: 25, inStock: true },
{ name: "Keyboard", price: 75, inStock: false }
])
Read: Finding Documents
findOne() retrieves the first document that matches a query, while find() retrieves all matching documents as a cursor.
JavaScript
// Find a single product with the name "Laptop"
> db.products.findOne({ name: "Laptop" })
// Find all products that are in stock
> db.products.find({ inStock: true })
// You can add a second argument to find() for "projection" - to specify which fields to return
// Find all products, but only show their names (the _id is always returned by default)
> db.products.find({}, { name: 1, _id: 0 })
Update: Modifying Documents
Use updateOne() or updateMany(). You must use update operators (like $set, $inc) to specify the change.
JavaScript
// Update the price of the Laptop. The first document is the filter, the second is the update.
> db.products.updateOne(
{ name: "Laptop" },
{ $set: { price: 1150, lastModified: new Date() } }
)
// Increase the price of all products by 5
> db.products.updateMany(
{}, // An empty filter matches all documents
{ $inc: { price: 5 } }
)
Delete: Removing Documents
Use deleteOne() or deleteMany() with a filter to specify which documents to remove.
JavaScript
// Delete the product named "Mouse"
> db.products.deleteOne({ name: "Mouse" })
// Delete all products that are not in stock
> db.products.deleteMany({ inStock: false })
Part 2: Using the Node.js Driver
In your application code, you'll use a driver to connect to and interact with MongoDB. Here’s how you perform the same CRUD operations in a Node.js script.
First, install the driver: npm install mongodb.
Code Snippet: crud.js
This script connects to a database, performs all four CRUD operations, and then closes the connection.
JavaScript
// crud.js
import { MongoClient } from 'mongodb';
// Connection URI
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
// Connect to the server
await client.connect();
console.log("Connected successfully to MongoDB");
const database = client.db("myNewStore");
const products = database.collection("products");
// --- CREATE ---
const insertResult = await products.insertMany([
{ name: "Webcam", price: 60, tags: ["video", "usb"] },
{ name: "Monitor", price: 300, tags: ["display", "hdmi"] }
]);
console.log(`Inserted ${insertResult.insertedCount} documents`);
// --- READ ---
const monitor = await products.findOne({ name: "Monitor" });
console.log("Found one monitor:", monitor);
// --- UPDATE ---
const updateResult = await products.updateOne(
{ name: "Webcam" },
{ $set: { price: 55 } }
);
console.log(`Updated ${updateResult.modifiedCount} document`);
// --- DELETE ---
const deleteResult = await products.deleteOne({ name: "Webcam" });
console.log(`Deleted ${deleteResult.deletedCount} document`);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);