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.
Section overview
5 resourcesCovers 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.
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