Handling CRUD Operations with MongoDB

Tutorial 2 of 5

1. Introduction

Goal of the Tutorial

In this tutorial, we are going to learn how to perform CRUD (Create, Retrieve, Update, Delete) operations in MongoDB using the MongoDB Node.js driver.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Connect to a MongoDB database
- Insert documents into a MongoDB database
- Query documents from a MongoDB database
- Update documents in a MongoDB database
- Delete documents from a MongoDB database

Prerequisites

  • Basic knowledge of JavaScript
  • Node.js installed on your machine
  • MongoDB installed on your machine

2. Step-by-Step Guide

Connecting to MongoDB

Before we can perform CRUD operations, we need to connect to a MongoDB database. We use the MongoClient.connect method to connect to the MongoDB server.

Inserting Documents

To insert documents into a MongoDB database, we use the insertOne or insertMany methods. The insertOne method inserts a single document into a collection, while the insertMany method inserts multiple documents.

Querying Documents

To query documents from a MongoDB database, we use the find method. We can pass in a query filter to find specific documents.

Updating Documents

To update a document in a MongoDB database, we use the updateOne or updateMany methods. We pass in a query filter to find the document(s) to update, and an update document that specifies the modifications to apply.

Deleting Documents

To delete a document from a MongoDB database, we use the deleteOne or deleteMany methods. We pass in a query filter to find the document(s) to delete.

3. Code Examples

Connecting to MongoDB

Here's an example of connecting to a MongoDB database.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected to MongoDB!");
  db.close();
});

Inserting Documents

Here's an example of inserting a document into a collection.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  let dbo = db.db("mydb");
  let myobj = { name: "John", age: "23" };
  dbo.collection("users").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });
});

Querying Documents

Here's an example of querying documents from a collection.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  let dbo = db.db("mydb");
  dbo.collection("users").find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

Updating Documents

Here's an example of updating a document in a collection.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  let dbo = db.db("mydb");
  let myquery = { name: "John" };
  let newvalues = { $set: {age: "25" } };
  dbo.collection("users").updateOne(myquery, newvalues, function(err, res) {
    if (err) throw err;
    console.log("1 document updated");
    db.close();
  });
});

Deleting Documents

Here's an example of deleting a document from a collection.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  let dbo = db.db("mydb");
  let myquery = { name: 'John' };
  dbo.collection("users").deleteOne(myquery, function(err, obj) {
    if (err) throw err;
    console.log("1 document deleted");
    db.close();
  });
});

4. Summary

In this tutorial, you've learned how to perform CRUD operations in MongoDB using the MongoDB Node.js driver. You've learned how to connect to a MongoDB database, insert documents, query documents, update documents, and delete documents.

5. Practice Exercises

To reinforce what you've learned, try the following exercises:

  1. Connect to a different MongoDB database and insert 5 documents into a collection.
  2. Query all documents in a collection that match a specific criteria.
  3. Update a specific document in a collection, and then query the document to confirm it was updated.
  4. Delete a specific document from a collection, and then query the collection to confirm it was deleted.

Remember, practice is the key to mastering any skill!