Using MongoDB with Node.js
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
Learn how to use MongoDB with Node.js, and understand the basics of NoSQL databases.
Introduction to MongoDB
MongoDB is a popular NoSQL database that allows you to store data in a flexible and scalable way. To use MongoDB with Node.js, you need to install the mongodb package. Run the following command in your terminal:
npm install mongodb
Step 1: Connect to MongoDB
Create a new file called app.js and add the following code to it:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';
MongoClient.connect(url, function(err, client) {
if (err) {
console.log(err);
} else {
console.log('Connected to MongoDB');
const db = client.db(dbName);
// Perform database operations
client.close);
}
});
Step 2: Create a Collection
Create a new collection called users:
const collection = db.collection('users');
Step 3: Insert Documents
Insert a new document into the users collection:
collection.insertOne({ name: 'John Doe', age: 30 }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Document inserted');
}
});
Step 4: Find Documents
Find all documents in the users collection:
collection.find().toArray(function(err, results) {
if (err) {
console.log(err);
} else {
console.log(results);
}
});
Step 5: Update Documents
Update a document in the users collection:
collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Document updated');
}
});
Step 6: Delete Documents
Delete a document from the users collection:
collection.deleteOne({ name: 'John Doe' }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Document deleted');
}
});
You can now use MongoDB with Node.js to perform various database operations.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Node.js courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Node.js books — check the publication year so the examples match current versions.
Search Amazon →