Node.js / Node.js REST APIs

Handling CRUD Operations with MongoDB

This tutorial introduces CRUD operations with MongoDB using the MongoDB Node.js driver. You will learn how to create a new MongoDB, insert documents, find documents with query fil…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores creating, testing, and securing RESTful APIs with Node.js and Express.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Scientific Calculator

Perform advanced math operations.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help