MongoDB / MongoDB Basics

Performing CRUD Operations in MongoDB

In this tutorial, you will learn how to perform CRUD (Create, Read, Update, and Delete) operations, which are the backbone of data management in MongoDB.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of MongoDB, including collections, documents, and CRUD operations.

1. Introduction

In this tutorial, our primary goal is to learn how to perform Create, Read, Update, and Delete (CRUD) operations in MongoDB. CRUD operations are the fundamental operations of any database application and MongoDB is no different.

By the end of this tutorial, you will learn how to:

  • Create new documents in MongoDB
  • Read documents from MongoDB
  • Update existing documents in MongoDB
  • Delete documents from MongoDB

As prerequisites, you should have MongoDB installed on your computer and basic understanding of JavaScript.

2. Step-by-Step Guide

Before we start, make sure you have MongoDB installed and running. Also, install the MongoDB Node.js driver using npm:

npm install mongodb

2.1 Creating a Connection

First, we need to connect to our MongoDB database. Here's how:

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

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

2.2 Creating a Collection

In MongoDB, a collection is like a table, and it holds documents. Here's how to create a collection:

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.createCollection("customers", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
    db.close();
  });
});

3. Code Examples

3.1 Creating Documents

In MongoDB, a document is like a record in a table. Let's create a new document:

var myobj = { name: "Company Inc", address: "Highway 37" };

dbo.collection("customers").insertOne(myobj, function(err, res) {
  if (err) throw err;
  console.log("1 document inserted");
  db.close();
});

3.2 Reading Documents

To read documents from a MongoDB collection, use the find method:

dbo.collection("customers").find({}).toArray(function(err, result) {
  if (err) throw err;
  console.log(result);
  db.close();
});

3.3 Updating Documents

To update a document, use the updateOne method:

var myquery = { address: "Valley 345" };
var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {
  if (err) throw err;
  console.log("1 document updated");
  db.close();
});

3.4 Deleting Documents

To delete a document, use the deleteOne method:

var myquery = { address: 'Mountain 21' };
dbo.collection("customers").deleteOne(myquery, function(err, obj) {
  if (err) throw err;
  console.log("1 document deleted");
  db.close();
});

4. Summary

In this tutorial, we learned how to perform CRUD operations in MongoDB. We've created a connection to MongoDB, created a collection, and performed Create, Read, Update, and Delete operations on documents.

To continue learning, you can explore more about MongoDB indexing, aggregation, and replication.

5. Practice Exercises

Exercise 1: Insert multiple documents into a collection using the insertMany method.

Exercise 2: Update multiple documents in a collection using the updateMany method.

Exercise 3: Delete multiple documents from a collection using the deleteMany method.

Refer to the MongoDB documentation for the methods' usage. Remember, practice is key to becoming proficient in MongoDB. Happy coding!

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

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

File Size Checker

Check the size of uploaded files.

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