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 data in a flexible, JSON-like format. 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').MongoClient;
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, function(err, client) {
if (err) {
console.log(err);
} else {
console.log('Connected to MongoDB');
}
});
This will connect to a MongoDB database running on the local machine.
Creating a Collection
Once you have a connection to the database, you can create a collection to store data. Here's an example:
const db = client.db();
const collection = db.collection('users');
This will create a new collection called users in the database.
Inserting Data
To insert data into the collection, you can use the insertOne method. Here's an example:
collection.insertOne({ name: 'John Doe', email: 'john@example.com' }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted data into collection');
}
});
This will insert a new document into the users collection with the name John Doe and email john@example.com.