MongoDB Query Document

MongoDB Query Document

MongoDB Query Document

Querying documents in MongoDB is essential for retrieving data from a database, such as fetching blog posts on a post-based website. This guide will walk you through how to query MongoDB documents step by step using Node.js, Express.js, and Mongoose.

1. Understanding MongoDB Query Operations

MongoDB provides multiple methods for querying documents, including:

MethodDescription
find(query)Retrieves all documents matching the query.
findOne(query)Retrieves a single document that matches the query.
findById(id)Retrieves a document by its unique _id.
find(query).limit(n)Retrieves a limited number of documents.
find(query).sort({ field: 1 or -1 })Sorts query results in ascending (1) or descending (-1) order.
find(query).select('field1 field2')Selects specific fields to return.

2. How Querying Works in a Post-Based Website

A. The Query Process

  1. The user requests posts based on filters (e.g., category, author, date).
  2. The server receives the request and retrieves matching documents.
  3. If matching posts are found, they are returned as a JSON response.
  4. If no posts exist, an appropriate error message is returned.

B. Example Use Cases

✅ Fetch all blog posts.
✅ Retrieve a single post by ID.
✅ Find posts by a specific author.
✅ Get the latest posts (sorted by date).
✅ Search for posts containing a keyword in the title.

3. Implementing MongoDB Queries in a Website

A. Connecting to MongoDB

Ensure MongoDB is running and properly connected.
(Refer to previous guides for setting up the database connection.)

B. Define the Blog Post Model

Create models/Post.js:

const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, author: { type: String, required: true }, category: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); const Post = mongoose.model('Post', postSchema); module.exports = Post;

C. Creating Query Routes

1️⃣ Retrieve All Posts

In routes/postRoutes.js, create a GET route:

const express = require('express'); const router = express.Router(); const Post = require('../models/Post'); // GET all posts router.get('/', async (req, res) => { try { const posts = await Post.find(); res.json(posts); } catch (error) { res.status(500).json({ message: "❌ Error fetching posts", error }); } }); module.exports = router;

Example Request:

curl -X GET http://localhost:3000/api/posts

Example Response:

[ { "_id": "65d1234abcde67890fgh1234", "title": "First Blog", "author": "John", "category": "Tech" }, { "_id": "65d5678xyz123456abcd5678", "title": "Second Blog", "author": "Jane", "category": "Health" } ]

2️⃣ Retrieve a Post by ID

// GET a post by ID router.get('/:id', async (req, res) => { try { const post = await Post.findById(req.params.id); if (!post) return res.status(404).json({ message: "⚠️ Post not found!" }); res.json(post); } catch (error) { res.status(500).json({ message: "❌ Error fetching post", error }); } });

Example Request:

curl -X GET http://localhost:3000/api/posts/65d1234abcde67890fgh1234

Example Response:

{ "_id": "65d1234abcde67890fgh1234", "title": "First Blog", "author": "John", "category": "Tech", "content": "This is my first blog post." }

3️⃣ Retrieve Posts by Author

// GET posts by a specific author router.get('/author/:author', async (req, res) => { try { const posts = await Post.find({ author: req.params.author }); res.json(posts); } catch (error) { res.status(500).json({ message: "❌ Error fetching posts by author", error }); } });

Example Request:

curl -X GET http://localhost:3000/api/posts/author/John

Example Response:

[ { "_id": "65d1234abcde67890fgh1234", "title": "First Blog", "author": "John" }, { "_id": "65d7890mnop456789qrst5678", "title": "Tech Innovations", "author": "John" } ]

4️⃣ Retrieve the Latest Posts (Sorted by Date)

// GET latest posts (sorted by creation date) router.get('/latest', async (req, res) => { try { const posts = await Post.find().sort({ createdAt: -1 }).limit(5); res.json(posts); } catch (error) { res.status(500).json({ message: "❌ Error fetching latest posts", error }); } });

Example Request:

curl -X GET http://localhost:3000/api/posts/latest

Example Response:

[ { "_id": "65d5678xyz123456abcd5678", "title": "Second Blog", "createdAt": "2025-02-02T14:00:00.000Z" }, { "_id": "65d1234abcde67890fgh1234", "title": "First Blog", "createdAt": "2025-02-02T12:00:00.000Z" } ]

5️⃣ Search for Posts by Keyword in Title

// GET posts with a keyword in the title router.get('/search/:keyword', async (req, res) => { try { const posts = await Post.find({ title: new RegExp(req.params.keyword, 'i') }); res.json(posts); } catch (error) { res.status(500).json({ message: "❌ Error searching posts", error }); } });

Example Request:

curl -X GET http://localhost:3000/api/posts/search/Tech

Example Response:

[ { "_id": "65d7890mnop456789qrst5678", "title": "Tech Innovations" }, { "_id": "65d1234abcde67890fgh1234", "title": "Latest Tech Trends" } ]

4. Summary

Queried MongoDB documents using Express.js & Mongoose.
Implemented multiple query types (by ID, author, keyword, latest posts).
Sorted & filtered results efficiently.

5. Next Steps

🔹 Implement Pagination for Large Queries
🔹 Add Indexing for Faster Search Performance
🔹 Enhance Query Security (Rate Limiting, Authentication)

Would you like help adding pagination or optimizing queries? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close