Node.js MongoDB CRUD Operations
Section (3.2) - Node.js MongoDB CRUD Operations
In this tutorial, we will explore CRUD operations in MongoDB with Node.js. CRUD stands for Create, Read, Update, and Delete. These are the essential operations needed to manage data in a database. We will cover the following topics:
- Creating a database and collections
- Inserting documents
- Reading documents
- Updating documents
- Deleting documents
Creating a Database and Collections
Before we dive into performing CRUD operations, we need to create a database and a collection to store our data. MongoDB stores data in BSON format, which is a binary representation of JSON. BSON allows MongoDB to store data efficiently and provides additional data types not found in JSON.
Setting up a Node.js Project
First, create a new directory for your Node.js project and initialize it with npm:
mkdir nodejs-mongodb-crud
cd nodejs-mongodb-crud
npm init -y
Next, install the mongodb
package:
npm install mongodb
Now, create a new file called index.js
in your project directory.
Connecting to a MongoDB Database
To connect to a MongoDB database, you need to use the MongoClient
object provided by the mongodb
package. Here's an example of how to connect to a local MongoDB server:
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useUnifiedTopology: true });
async function main() {
try {
await client.connect();
// Perform CRUD operations here
} finally {
await client.close();
}
}
main().catch(console.error);
Replace the uri
variable with the connection string for your MongoDB server. If you're using a remote server or a MongoDB Atlas cluster, use the appropriate connection string provided by your provider.
Creating a Database and a Collection
In MongoDB, you don't need to explicitly create a database or a collection. When you insert a document into a collection that does not exist, MongoDB automatically creates the database and collection for you. However, it's a good practice to create the collection with the desired options beforehand.
Here's an example of how to create a database called mydb
and a collection called users
:
async function main() {
try {
await client.connect();
const db = client.db('mydb');
const usersCollection = await db.createCollection('users');
// Perform CRUD operations on the users collection
} finally {
await client.close();
}
}
Inserting Documents
Once you've set up your database and collection, you can start inserting documents. A document in MongoDB is a JSON-like object that can store data with complex structures, such as nested objects and arrays.
Inserting a Single Document
To insert a single document, use the insertOne()
method:
const newUser = {
name: 'John Doe',
age: 25,
email: 'john.doe@example.com',
};
const result = await usersCollection.insertOne(newUser);
console.log('Inserted document with _id:', result.insertedId);
Inserting Multiple Documents
To insert multiple documents at once, use the insertMany()
method:
const users = [
{
name: 'Jane Doe',
age: 28,
email: 'jane.doe@example.com',
},
{
name: 'Alice',
age: 30,
email: 'alice@example.com',
},
];
const result = await usersCollection.insertMany(users);
console.log('Inserted documents with _ids:', result.insertedIds);
Reading Documents
To retrieve documents from a collection, you can use the find()
and findOne()
methods.
Finding a Single Document
To find a single document that matches a query, use the findOne()
method:
const query = { name: 'John Doe' };
const user = await usersCollection.findOne(query);
if (user) {
console.log('Found user:', user);
} else {
console.log('User not found');
}
Finding Multiple Documents
To find multiple documents that match a query, use the find()
method. This method returns a cursor, which allows you to iterate over the result set:
const query = { age: { $gte: 25 } };
const cursor = usersCollection.find(query);
await cursor.forEach((user) => {
console.log('Found user:', user);
});
You can also convert the cursor to an array of documents using the toArray()
method:
const users = await cursor.toArray();
console.log('Found users:', users);
Using Projection
Projection allows you to control the fields returned in the query results. To include or exclude specific fields, pass a projection object to the find()
or findOne()
methods:
const query = { name: 'John Doe' };
const projection = { _id: 0, name: 1, email: 1 };
const user = await usersCollection.findOne(query, { projection });
console.log('Found user:', user);
In this example, the _id
field is excluded from the result, and only the name
and email
fields are included.
Updating Documents
To update documents in a collection, you can use the updateOne()
and updateMany()
methods.
Updating a Single Document
To update a single document that matches a query, use the updateOne()
method:
const filter = { name: 'John Doe' };
const update = { $set: { age: 26 } };
const result = await usersCollection.updateOne(filter, update);
console.log('Updated', result.modifiedCount, 'documents');
Updating Multiple Documents
To update multiple documents that match a query, use the updateMany()
method:
const filter = { age: { $gte: 25 } };
const update = { $inc: { age: 1 } };
const result = await usersCollection.updateMany(filter, update);
console.log('Updated', result.modifiedCount, 'documents');
Deleting Documents
To delete documents from a collection, you can use the deleteOne()
and deleteMany()
methods.
Deleting a Single Document
To delete a single document that matches a query, use the deleteOne()
method:
const filter = { name: 'John Doe' };
const result = await usersCollection.deleteOne(filter);
console.log('Deleted', result.deletedCount, 'documents');
Deleting Multiple Documents
To delete multiple documents that match a query, use the deleteMany()
method:
const filter = { age: { $lt: 25 } };
const result = await usersCollection.deleteMany(filter);
console.log('Deleted', result.deletedCount, 'documents');
FAQs
Q: What are CRUD operations?
A: CRUD stands for Create, Read, Update, and Delete. These operations are the essential actions needed to manage data in a database.
Q: Why use MongoDB with Node.js?
A: MongoDB is a popular NoSQL database that provides high performance, flexibility, and scalability. It stores data in BSON format, which is a binary representation of JSON. Node.js is well-suited for working with JSON-like data, making it an excellent choice for using MongoDB.
Q: How do I connect to a MongoDB database in Node.js?
A: First, install the mongodb
package using npm. Then, use the MongoClient
object provided by the mongodb
package to connect to your MongoDB server. You will need to provide the connection string for your MongoDB server.
Q: How do I perform CRUD operations in MongoDB with Node.js?
A: Use the following methods to perform CRUD operations on a MongoDB collection:
insertOne()
andinsertMany()
for creating documents.findOne()
andfind()
for reading documents.updateOne()
andupdateMany()
for updating documents.deleteOne()
anddeleteMany()
for deleting documents.
Q: How do I query documents in MongoDB using Node.js?
A: Use the findOne()
method to find a single document that matches a query, and use the find()
method to find multiple documents that match a query. You can pass a query object to these methods to filter the documents returned.
Q: How do I update documents in MongoDB using Node.js?
A: Use the updateOne()
method to update a single document that matches a query, and use the updateMany()
method to update multiple documents that match a query. You can pass a filter object to match the documents to update and an update object to specify the update operations to apply.
Q: How do I delete documents in MongoDB using Node.js?
A: Use the deleteOne()
method to delete a single document that matches a query, and use the deleteMany()
method to delete multiple documents that match a query. You can pass a filter object to these methods to match the documents to delete.