Recent Post:
Categories:
Querying MongoDB in a Next.js application allows you to fetch and manipulate data efficiently. Here’s how you can perform various queries:
Fetch all documents from a collection.
code
// pages/api/posts.js
import clientPromise from '../../lib/mongodb';
export default async function handler(req, res) {
const client = await clientPromise;
const db = client.db('mydatabase');
const posts = await db.collection('posts').find().toArray();
res.status(200).json(posts);
}
Fetch documents based on specific criteria.
code
// pages/api/posts.js
import clientPromise from '../../lib/mongodb';
export default async function handler(req, res) {
const client = await clientPromise;
const db = client.db('mydatabase');
const { author } = req.query;
const posts = await db.collection('posts').find({ author }).toArray();
res.status(200).json(posts);
}
Perform complex queries using the aggregation framework.
By mastering these querying techniques, you can handle data more effectively in your Next.js applications, ensuring you can meet various data requirements.
code
// pages/api/posts.js
import clientPromise from '../../lib/mongodb';
export default async function handler(req, res) {
const client = await clientPromise;
const db = client.db('mydatabase');
const posts = await db
.collection('posts')
.aggregate([{ $match: { author: 'John Doe' } }, { $group: { _id: '$category', count: { $sum: 1 } } }])
.toArray();
res.status(200).json(posts);
};