Introduction to MongoDB and Node.js
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.