MongoDB Get Started

MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). Unlike traditional relational databases, MongoDB allows developers to handle large datasets and rapidly changing requirements with ease.

Why Choose MongoDB?

  1. Flexibility: MongoDB uses a schema-less structure, meaning you don’t need to predefine tables and columns like relational databases.
  2. Scalability: It supports horizontal scaling, making it ideal for handling large amounts of data.
  3. Performance: MongoDB provides high performance for read and write operations.
  4. Ease of Use: Its syntax is intuitive and similar to JSON, making it beginner-friendly.

Prerequisites

  1. Node.js Installed: Download and install Node.js from nodejs.org.
  2. MongoDB Installed: Download MongoDB from mongodb.com.

Step 1: Install MongoDB

On Windows:

  1. Download MongoDB Community Server from MongoDB Downloads.
  2. Run the installer and follow the setup instructions.
  3. During installation, select “Complete” setup and ensure the “Install MongoDB as a Service” option is checked.

On macOS:

Use Homebrew to install MongoDB:

brew tap mongodb/brew
brew install mongodb-community

Start the MongoDB service:

brew services start mongodb/brew/mongodb-community

On Linux:

Follow the official MongoDB installation instructions for your distribution: Install MongoDB on Linux.

Start the MongoDB service:

sudo systemctl start mongod

Step 2: Verify MongoDB Installation

After installation, verify MongoDB is running by opening a terminal and typing:

mongod --version

You should see the installed version of MongoDB.

To start the MongoDB shell (a command-line interface for MongoDB), type:

mongosh

Step 3: Install MongoDB Node.js Driver

To use MongoDB in your Node.js applications, you need to install the official MongoDB driver.

Run the following command in your Node.js project directory:

npm install mongodb

Step 4: Connect to MongoDB

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

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');

// Select the database
const db = client.db(dbName);

// Perform operations (example: list collections)
const collections = await db.listCollections().toArray();
console.log('Collections:', collections);
} catch (err) {
console.error('Error connecting to MongoDB:', err);
} finally {
// Close the connection
await client.close();
}
}

main();

Explanation:

  • MongoClient: The MongoDB client for connecting to the database.
  • localhost:27017: The default MongoDB connection URL.
  • myDatabase: The database name (MongoDB will create it automatically if it doesn’t exist).

Step 5: Basic MongoDB Commands

Here are some essential MongoDB operations with examples:

1. Create a Collection

Collections in MongoDB are equivalent to tables in relational databases.

const collection = db.collection('users');

2. Insert Documents

Documents are equivalent to rows in relational databases.

const result = await collection.insertOne({ name: 'Alice', age: 25, city: 'New York' });
console.log('Inserted document ID:', result.insertedId);

To insert multiple documents:

const result = await collection.insertMany([
{ name: 'Bob', age: 30, city: 'London' },
{ name: 'Charlie', age: 35, city: 'San Francisco' },
]);
console.log('Inserted documents count:', result.insertedCount);

3. Query Documents

Retrieve documents from a collection using the find method.

const users = await collection.find({ city: 'New York' }).toArray();
console.log('Users from New York:', users);

4. Update Documents

Update a document in the collection.

const result = await collection.updateOne(
{ name: 'Alice' }, // Filter
{ $set: { age: 26 } } // Update
);
console.log('Matched documents:', result.matchedCount);
console.log('Modified documents:', result.modifiedCount);

5. Delete Documents

Remove documents from a collection.

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

Real-World Use Case

Imagine building a user management system where you can:

  1. Add new users to the database.
  2. Retrieve user details based on criteria.
  3. Update user profiles.
  4. Delete inactive users.

Example: CRUD Operations

async function manageUsers() {
const collection = db.collection('users');

// Create
await collection.insertOne({ name: 'John', age: 28, city: 'Paris' });

// Read
const user = await collection.findOne({ name: 'John' });
console.log('User:', user);

// Update
await collection.updateOne({ name: 'John' }, { $set: { age: 29 } });

// Delete
await collection.deleteOne({ name: 'John' });
}
manageUsers();

Leave a Comment

BoxofLearn