Introduction to MongoDB and 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 to store and retrieve data.
Introduction to MongoDB
MongoDB is a popular NoSQL database that allows you to store and manage large amounts of data. To get started with MongoDB, you'll need to install the mongodb package in Node.js. You can do this by running npm install mongodb in your terminal.
Connecting to MongoDB
To connect to a MongoDB database, you can use the following code:
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'example';
MongoClient.connect(url, function(err, client) {
if (err) {
console.log(err);
} else {
console.log('Connected to MongoDB');
const db = client.db(dbName);
// Perform operations on the database
client.close();
}
});
This will connect to a MongoDB database on the local machine and log a success message to the console.
Creating a Collection
Once you have a database, you can create a collection using the following code:
const collection = db.collection('users');
This will create a new collection called users in the database.
Inserting Data
To insert data into the users collection, you can use the following code:
collection.insertOne({ name: 'John Doe', email: 'john@example.com' }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted data into MongoDB');
}
});
This will insert a new document into the users collection with the name John Doe and email john@example.com.
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 MongoDB 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 MongoDB books — check the publication year so the examples match current versions.
Search Amazon →