MongoDB Collection

In MongoDB, a collection is a group of documents, similar to a table in relational databases. Collections are schema-less, meaning each document in a collection can have a different structure.

What Is a MongoDB Collection?

A collection in MongoDB is:

  1. A Logical Container: Collections store multiple documents.
  2. Dynamic and Flexible: Unlike relational databases, you don’t need to predefine the schema for a collection.
  3. Independent: Collections in the same database can store completely different types of data.

Key Features of MongoDB Collections

  • Dynamic Schemas: Collections allow documents with different structures to coexist.
  • Automatic Creation: Collections are created dynamically when you insert the first document.
  • Efficient Storage: MongoDB uses BSON (Binary JSON) format for efficient storage and retrieval.

Prerequisites

  1. MongoDB Installed: Download MongoDB from mongodb.com.
  2. Node.js Installed: Download and install Node.js from nodejs.org.
  3. MongoDB Shell or Compass: Use the MongoDB shell (CLI) or Compass (GUI).

Method 1: Create a Collection Using MongoDB Shell

Step 1: Open the MongoDB Shell

Run the following command to open the MongoDB shell:

mongosh

Step 2: Switch to the Database

Use the use command to select or create a database:

use myDatabase

Step 3: Create a Collection

Collections are created automatically when you insert the first document:

db.users.insertOne({ name: 'Alice', age: 25 });

Alternatively, you can explicitly create a collection:

db.createCollection('users');

Verify the Collection

List all collections in the database:

show collections

Method 2: Create a Collection Using Node.js

Step 1: Install MongoDB Driver

Run the following command to install the MongoDB driver:

npm install mongodb

Step 2: Create a Collection in Node.js

Create a file named app.js and write the following code:

const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myDatabase';

async function main() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected successfully to MongoDB');

// Create or use the database
const db = client.db(dbName);

// Create a collection
const collection = await db.createCollection('users');
console.log('Collection created:', collection.collectionName);

// Insert a document into the collection
const result = await collection.insertOne({ name: 'Bob', age: 30 });
console.log('Document inserted with ID:', result.insertedId);
} catch (err) {
console.error('Error:', err);
} finally {
// Close the connection
await client.close();
}
}

main();

Method 3: Create a Collection Using MongoDB Compass

MongoDB Compass provides a graphical interface for database and collection management.

Step 1: Open MongoDB Compass

  1. Launch the Compass application.
  2. Connect to your MongoDB server (default is mongodb://localhost:27017).

Step 2: Create a Collection

  1. Select your database or create a new one.
  2. Click “Create Collection”.
  3. Enter the collection name (e.g., users) and optional validation rules.
  4. Click “Create” to save the collection.

CRUD Operations on a Collection

Once a collection is created, you can perform CRUD (Create, Read, Update, Delete) operations.

1. Insert Documents

const result = await db.collection('users').insertOne({ name: 'Emma', age: 27 });
console.log('Inserted document ID:', result.insertedId);

2. Read Documents

const users = await db.collection('users').find({ age: { $gt: 25 } }).toArray();
console.log('Users older than 25:', users);

3. Update Documents

const result = await db.collection('users').updateOne(
{ name: 'Emma' },
{ $set: { age: 28 } }
);
console.log('Updated documents:', result.modifiedCount);

4. Delete Documents

const result = await db.collection('users').deleteOne({ name: 'Emma' });
console.log('Deleted documents:', result.deletedCount);

Real-World Use Case

Imagine creating an inventory management system. Each product can be stored as a document in a products collection.

Example: Managing Products

async function manageProducts() {
const db = client.db('inventory');
const collection = db.collection('products');

// Insert a product
await collection.insertOne({ name: 'Laptop', price: 1000, stock: 50 });

// Retrieve all products
const products = await collection.find().toArray();
console.log('Products:', products);

// Update stock for a product
await collection.updateOne({ name: 'Laptop' }, { $inc: { stock: -1 } });

// Delete a product
await collection.deleteOne({ name: 'Laptop' });
}
manageProducts();

Leave a Comment

BoxofLearn