In this section, we will explore how to use MongoDB with JavaScript, specifically using Node.js. Node.js is a popular runtime environment that allows you to run JavaScript on the server side. MongoDB, being a NoSQL database, pairs well with JavaScript due to its JSON-like document structure.
Table of Contents
Setting Up the Environment
Before we start, ensure you have Node.js and npm (Node Package Manager) installed on your machine. You can download them from Node.js official website.
Step-by-Step Setup
-
Initialize a new Node.js project:
mkdir mongodb-nodejs cd mongodb-nodejs npm init -y
-
Install the MongoDB Node.js driver:
npm install mongodb
-
Create a new JavaScript file:
touch index.js
Connecting to MongoDB
To connect to MongoDB, you need to use the MongoDB Node.js driver. Here’s a basic example of how to connect to a MongoDB database:
const { MongoClient } = require('mongodb'); async function main() { const uri = "mongodb://localhost:27017"; // Connection URI const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); try { await client.connect(); console.log("Connected to MongoDB"); } catch (e) { console.error(e); } finally { await client.close(); } } main().catch(console.error);
Explanation:
- MongoClient: This is the main class for connecting to a MongoDB server.
- uri: The connection string to your MongoDB server.
- client.connect(): Establishes a connection to the MongoDB server.
- client.close(): Closes the connection.
CRUD Operations
Create
To insert documents into a MongoDB collection, you can use the insertOne
or insertMany
methods.
async function createDocument(client) { const result = await client.db("sampleDB").collection("sampleCollection").insertOne({ name: "John Doe", age: 30, address: "123 Main St" }); console.log(`New document created with the following id: ${result.insertedId}`); }
Read
To read documents from a MongoDB collection, you can use the findOne
or find
methods.
async function readDocument(client) { const result = await client.db("sampleDB").collection("sampleCollection").findOne({ name: "John Doe" }); if (result) { console.log(`Found a document in the collection with the name 'John Doe':`, result); } else { console.log("No document found with the name 'John Doe'"); } }
Update
To update documents in a MongoDB collection, you can use the updateOne
or updateMany
methods.
async function updateDocument(client) { const result = await client.db("sampleDB").collection("sampleCollection").updateOne( { name: "John Doe" }, { $set: { age: 31 } } ); console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`); }
Delete
To delete documents from a MongoDB collection, you can use the deleteOne
or deleteMany
methods.
async function deleteDocument(client) { const result = await client.db("sampleDB").collection("sampleCollection").deleteOne({ name: "John Doe" }); console.log(`${result.deletedCount} document(s) was/were deleted.`); }
Practical Exercises
Exercise 1: Insert Multiple Documents
Task: Write a function to insert multiple documents into a collection.
async function createMultipleDocuments(client) { const result = await client.db("sampleDB").collection("sampleCollection").insertMany([ { name: "Alice", age: 25, address: "456 Elm St" }, { name: "Bob", age: 28, address: "789 Oak St" } ]); console.log(`${result.insertedCount} new document(s) created with the following id(s):`); console.log(result.insertedIds); }
Exercise 2: Find Multiple Documents
Task: Write a function to find all documents in a collection where the age is greater than 25.
async function findDocuments(client) { const cursor = await client.db("sampleDB").collection("sampleCollection").find({ age: { $gt: 25 } }); const results = await cursor.toArray(); if (results.length > 0) { console.log("Found documents:"); results.forEach((result, i) => { console.log(); console.log(`${i + 1}. name: ${result.name}`); console.log(` age: ${result.age}`); console.log(` address: ${result.address}`); }); } else { console.log("No documents found"); } }
Summary
In this section, we covered how to set up a Node.js environment to work with MongoDB, how to connect to a MongoDB database, and how to perform basic CRUD operations. We also provided practical exercises to reinforce the concepts learned.
By mastering these basics, you are now prepared to build more complex applications using MongoDB and Node.js. In the next sections, we will delve deeper into advanced MongoDB features and how to integrate them into your applications.