Exploring MongoDB: A Beginner’s Guide

Ayushmaan Srivastav
5 min readApr 20, 2024

--

Welcome to our MongoDB journey, where we delve into the world of NoSQL databases and learn the ropes of MongoDB, a powerful and flexible document-oriented database. In this blog, we’ll cover essential topics with practical examples and MongoDB commands, making your learning experience both enjoyable and fruitful. Let’s dive in!

🐚 The MongoDB Shell

MongoDB provides a versatile command-line interface called the Mongo Shell, your gateway to interacting with databases and executing commands.

📄 BSON: Binary JSON

BSON (Binary JSON) is the data format used by MongoDB to store documents in a binary-encoded format. It extends JSON by supporting additional data types and provides efficient storage and traversal of data.

📑 Document vs Collection

In MongoDB, data is stored in collections, which are analogous to tables in relational databases. Each collection contains documents, which are JSON-like data structures representing individual records.

➕ INSERT in DB

To add a document to a collection, we use the insertOne() or insertMany() method. Here's a quick example:

db.collection.insertOne({ name: "John", age: 30 });

🔍 Find in DB

The find() method is used to retrieve documents from a collection based on specified criteria. For instance:

db.collection.find({ age: { $gte: 25 } });

🔎 Query Operators

MongoDB provides a variety of query operators to perform precise searches. Examples include $eq, $gt, $lt, $in, and more.

🔄 UPDATE in DB

To modify existing documents, we use the updateOne() or updateMany() method. Here's a simple update operation:

db.collection.updateOne({ name: "John" }, { $set: { age: 35 } });

🔧 Update Operators

MongoDB offers update operators like $set, $inc, $push, etc., for granular control over update operations.

📦 Nesting

Documents in MongoDB can be nested, allowing for hierarchical data structures. This feature enables complex data modeling and querying.

➖ DELETE in DB

To remove documents from a collection, we use the deleteOne() or deleteMany() method. For example:

db.collection.deleteOne({ name: "John" });

📡 Mongoose: Elegant MongoDB Object Modeling for Node.js

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment like Node.js. It provides a straightforward schema-based solution to model application data.

📋 Schema and Models

In Mongoose, a schema defines the structure of documents within a collection, while models are constructors compiled from these schemas, providing an interface to interact with the database.

➕ Insert in Mongoose

Adding documents in Mongoose is similar to vanilla MongoDB, but with the convenience of Mongoose schemas and models.

const user = new User({ name: "Alice", age: 25 });
user.save();

➕ Insert Multiple

Inserting multiple documents in Mongoose can be done efficiently using the insertMany() method.

User.insertMany([{ name: "Bob", age: 30 }, { name: "Charlie", age: 35 }]);

🔍 Find in Mongoose

Querying in Mongoose involves using methods like find(), findOne(), or chaining query conditions for precise retrieval.

🔄 Update in Mongoose

Updating documents in Mongoose follows a similar pattern to MongoDB’s update operations but integrates seamlessly with Mongoose models.

🔍 Find and Update in Mongoose

Mongoose provides the findOneAndUpdate() method to atomically find a document and apply updates.

User.findOneAndUpdate({ name: "Alice" }, { $set: { age: 26 } });

➖ Delete in Mongoose

Deleting documents in Mongoose can be achieved using methods like deleteOne() or deleteMany(), similar to MongoDB.

🔐 Schema Validations

Mongoose schemas support validations to ensure data integrity. Define validation rules within schemas to enforce data constraints.

🔍 Schematype Options

Schematype options allow fine-tuning of schema fields, including specifying default values, defining getters/setters, and more.

🛠️ Validation in Updation

When updating documents in Mongoose, schema validations are automatically applied, ensuring that updated data complies with defined rules.

Building a RESTful API with MongoDB and Express.js using Mongoose

Below is an example code snippet demonstrating how to use MongoDB with Express.js using Mongoose, a popular MongoDB object modeling tool for Node.js applications. This example includes setting up a basic Express server, connecting to a MongoDB database using Mongoose, defining a simple schema, and performing CRUD operations (Create, Read, Update, Delete).

// Import required packages
const express = require('express');
const mongoose = require('mongoose');

// Initialize Express app
const app = express();
const port = 3000;

// Connect to MongoDB database using Mongoose
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB:', err));

// Define a Mongoose schema
const todoSchema = new mongoose.Schema({
title: String,
completed: Boolean
});

// Create a Mongoose model based on the schema
const Todo = mongoose.model('Todo', todoSchema);

// Middleware to parse JSON requests
app.use(express.json());

// Route to create a new todo item
app.post('/todos', async (req, res) => {
try {
const todo = new Todo(req.body);
await todo.save();
res.status(201).send(todo);
} catch (err) {
res.status(400).send(err);
}
});

// Route to get all todo items
app.get('/todos', async (req, res) => {
try {
const todos = await Todo.find();
res.send(todos);
} catch (err) {
res.status(500).send(err);
}
});

// Route to update a todo item by ID
app.patch('/todos/:id', async (req, res) => {
try {
const todo = await Todo.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(todo);
} catch (err) {
res.status(400).send(err);
}
});

// Route to delete a todo item by ID
app.delete('/todos/:id', async (req, res) => {
try {
const todo = await Todo.findByIdAndDelete(req.params.id);
res.send(todo);
} catch (err) {
res.status(400).send(err);
}
});

// Start the Express server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

In this example:

  1. We import the required packages, which are Express and Mongoose.
  2. Express app is initialized, and a connection to the MongoDB database is established using Mongoose.
  3. A Mongoose schema todoSchema is defined to represent the structure of todo items with two fields: title (String) and completed (Boolean).
  4. A Mongoose model Todo is created based on the schema.
  5. Middleware is added to parse JSON requests.
  6. Express routes are defined for creating, reading, updating, and deleting todo items.
  • POST /todos creates a new todo item.
  • GET /todos retrieves all todo items.
  • PATCH /todos/:id updates a todo item by its ID.
  • DELETE /todos/:id deletes a todo item by its ID.

7. The Express server is started, listening on port 3000.

This code provides a basic foundation for building a RESTful API using Express.js and MongoDB with Mongoose.

--

--

No responses yet