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:
As prerequisites, you should have MongoDB installed on your computer and basic understanding of JavaScript.
Before we start, make sure you have MongoDB installed and running. Also, install the MongoDB Node.js driver using npm:
npm install mongodb
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();
});
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();
});
});
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();
});
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();
});
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();
});
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();
});
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.
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!