Mongodb Show Collection

Mongodb Show Collection

Mongodb Show Collection

In MongoDB, collections store documents, similar to tables in relational databases. This guide explains how to list all collections in a database using MongoDB Shell, Node.js (Mongoose), and Compass.

1. Show Collections Using MongoDB Shell

A. Open MongoDB Shell

Start the MongoDB shell by running:

mongosh

B. Select a Database

Choose the database you want to list collections for:

use blogDB

C. List All Collections

Run the following command:

show collections

Example Output:

posts users comments

This displays all collections inside blogDB.

2. Show Collections Using Node.js (Mongoose)

A. Install Mongoose (If Not Installed)

npm install mongoose

B. Create a Script to List Collections

Create listCollections.js:

const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("✅ Connected to MongoDB")) .catch(err => console.error("❌ Connection Error:", err)); async function listCollections() { try { const collections = await mongoose.connection.db.listCollections().toArray(); console.log("📂 Collections in 'blogDB':"); collections.forEach(collection => console.log(`- ${collection.name}`)); } catch (error) { console.log("❌ Error listing collections:", error.message); } finally { mongoose.connection.close(); } } listCollections();

Run the script:

node listCollections.js

Example Output:

📂 Collections in 'blogDB': - posts - users - comments

3. Show Collections Using Express.js API

A. Modify routes/dbRoutes.js

const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); // GET - List all collections router.get('/collections', async (req, res) => { try { const collections = await mongoose.connection.db.listCollections().toArray(); res.json(collections.map(col => col.name)); } catch (error) { res.status(400).json({ message: "❌ Error listing collections", error: error.message }); } }); module.exports = router;

B. Test the API (Using cURL or Postman)

curl -X GET http://localhost:3000/api/db/collections

Example Response:

["posts", "users", "comments"]

4. Show Collections Using MongoDB Compass

If you prefer a graphical interface, use MongoDB Compass:

  1. Open MongoDB Compass and connect to your database.
  2. Click on the database name (e.g., blogDB).
  3. You will see a list of all collections in that database.

The collections will be displayed on the screen.

5. Summary

Listed collections using MongoDB Shell (show collections).
Used Mongoose to list collections via a script.
Created an Express.js API to fetch collections dynamically.
Used MongoDB Compass for a GUI-based approach.

6. Next Steps

🔹 Filter collections based on specific criteria.
🔹 Implement authentication to secure database queries.
🔹 Monitor database usage and optimize queries.

Would you like help with database security or query optimization? 🚀

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