TechieClues TechieClues
Updated date Apr 08, 2023
Learn how to perform create, read, update, and delete operations in MongoDB using Node.js. This guide provides sample code for each operation and covers important considerations when working with MongoDB and Node.js.

Introduction:

MongoDB is a popular NoSQL database that provides great scalability, high performance, and document-oriented storage. CRUD operations are the basic building blocks of any database system, including MongoDB. CRUD stands for Create, Read, Update, and Delete. In this article, we will cover how to perform CRUD operations in MongoDB.

Before we dive into the actual code, let's first understand what each operation means:

  • Create: This operation allows you to insert new documents into a MongoDB collection. A document is a data structure that consists of field-value pairs, similar to a JSON object.
  • Read: This operation allows you to retrieve data from a MongoDB collection. You can retrieve a single document or multiple documents that match a specific query.
  • Update: This operation allows you to modify existing documents in a MongoDB collection. You can update one or multiple documents that match a specific query.
  • Delete: This operation allows you to remove documents from a MongoDB collection. You can delete a single document or multiple documents that match a specific query.

Now that we know what each operation does, let's move on to the actual code.

Prerequisites Before we start coding, we need to make sure we have MongoDB installed on our system. You can download MongoDB from the official website: https://www.mongodb.com/download-center/community.

We will also need a MongoDB driver for our programming language. In this article, we will be using the official MongoDB driver for Node.js. You can install it by running the following command:

npm install mongodb

Create Operation:

To create a new document in a MongoDB collection, we first need to establish a connection to the database. We can do this by using the MongoClient object provided by the MongoDB driver. Once we have a connection, we can then insert a new document using the insertOne() method.

Here's an example:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  const dbo = db.db('mydb');
  const newDocument = { name: 'John', age: 30 };
  dbo.collection('customers').insertOne(newDocument, function(err, res) {
    if (err) throw err;
    console.log('1 document inserted');
    db.close();
  });
});

In this example, we first import the MongoClient object and set the URL for our MongoDB database. We then establish a connection to the database by calling the connect() method. Once we have a connection, we create a new document with the name "John" and age 30. We then use the insertOne() method to insert the new document into the "customers" collection. Finally, we log a message to the console indicating that the document was successfully inserted, and we close the database connection.

Output:

1 document inserted

Read Operation:

To retrieve data from a MongoDB collection, we can use the find() method. The find() method returns a cursor, which we can iterate over to retrieve the documents that match a specific query. We can also pass a query object as an argument to the find() method to retrieve only the documents that match the query.

Here's an example:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  const dbo = db.db('mydb');
  const query = { name: 'John' };
  dbo.collection('customers').find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

In this example, we first import the MongoClient object and set the URL for our MongoDB database. We then establish a connection to the database by calling the connect() method. Once we have a connection, we create a query object that specifies that we want to retrieve all documents where the name is "John". We then use the find() method to retrieve the documents that match the query. Finally, we log the result to the console and close the database connection.

Output:

[{ "_id" : ObjectId("606b46851daea36515b93d84"), "name" : "John", "age" : 30 }]

Update Operation:

To update an existing document in a MongoDB collection, we can use the updateOne() method. The updateOne() method takes two arguments: a query object that specifies which documents to update, and an update object that specifies how to update the documents.

Here's an example:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  const dbo = db.db('mydb');
  const query = { name: 'John' };
  const update = { $set: { age: 40 } };
  dbo.collection('customers').updateOne(query, update, function(err, res) {
    if (err) throw err;
    console.log('1 document updated');
    db.close();
  });
});

In this example, we first import the MongoClient object and set the URL for our MongoDB database. We then establish a connection to the database by calling the connect() method. Once we have a connection, we create a query object that specifies which documents to update (in this case, all documents with the name "John"). We then create an update object that uses the $set operator to set the age field to 40. Finally, we use the updateOne() method to update the documents that match the query, log a message to the console indicating that the document was successfully updated, and close the database connection.

Output:

1 document updated

Delete Operation:

To delete a document from a MongoDB collection, we can use the deleteOne() method. The deleteOne() method takes a query object as an argument that specifies which document to delete.

Here's an example:

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  const dbo = db.db('mydb');
  const query = { name: 'John' };
  dbo.collection('customers').deleteOne(query, function(err, res) {
    if (err) throw err;
    console.log('1 document deleted');
    db.close();
  });
});

In this example, we first import the MongoClient object and set the URL for our MongoDB database. We then establish a connection to the database by calling the connect() method. Once we have a connection, we create a query object that specifies which document to delete (in this case, the document with the name "John"). We then use the deleteOne() method to delete the document that matches the query, log a message to the console indicating that the document was successfully deleted, and close the database connection.

Output:

1 document deleted

Conclusion:

In this article, we have covered how to perform CRUD operations in MongoDB using Node.js. We covered the basic concepts of create, read, update, and delete, and we provided sample codes for each operation. By understanding these concepts, you should now have a solid foundation for building more complex database applications using MongoDB and Node.js.

Some additional points to keep in mind when working with MongoDB and Node.js:

  1. Always close the database connection when you're done working with the database. This will prevent memory leaks and other issues.
  2. Use indexes to optimize query performance. Indexes can greatly improve the speed of queries, especially for large collections.
  3. Be careful when performing updates, especially with the $set operator. Make sure you understand exactly what fields you're updating and how the update will affect your data.
  4. Use the findOne() method to retrieve a single document that matches a query. This method is faster than the find() method if you only need to retrieve one document.
  5. Use the insertMany() method to insert multiple documents into a collection. This method is faster than inserting documents one by one.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!