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…
Section overview
5 resourcesExplores 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:
- Connect to a different MongoDB database and insert 5 documents into a collection.
- Query all documents in a collection that match a specific criteria.
- Update a specific document in a collection, and then query the document to confirm it was updated.
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article