CRUD operations in MongoDB

CRUD operations in MongoDB

CRUD operations are the core of MongoDB and they are used to Create, Read, Update and Delete documents in MongoDB collections. These operations can be performed using various methods provided by MongoDB driver. The most commonly used methods are insertOne(), find(), updateOne(), and deleteOne(). Understanding these basic operations are important

MongoDB is a NoSQL, document-oriented database that is designed to handle large amounts of data across many commodity servers. It is an open-source database, meaning that it is freely available to use and modify. MongoDB is known for its ability to handle unstructured data, horizontal scalability, and high availability, making it a popular choice for  companies like Scrrum Labs  to build  applications and provide services  that require flexible and scalable data management.

One of the core features of MongoDB is its support for CRUD (Create, Read, Update, and Delete) operations. In this beginner's guide, we will take a closer look at these operations and how to perform them using MongoDB in our application.


Create: The first step in working with MongoDB is to create a new document. A document in MongoDB is similar to a row in a traditional SQL database. Documents are stored in collections, which are similar to tables in SQL databases. To create a new document, you can use the insert() method. The insert() method takes a single document or an array of documents as an argument and adds them to the specified collection.

Here is an example of how you can use the insert() method to create a new document 

const MongoClient = require('mongodb').MongoClient;

const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // create a new document
  const document = { name: "Smartphone", price: 800 };
  // insert the document into the "devices" collection
  collection.insertOne(document, function(err, res) {
    console.log("Document inserted");
    client.close();
  });
});

. We created a new document with a name and price field by  using  the insertOne() method to insert it into the "devices"

Read: Once you have created documents in MongoDB, you can read them using the find() method. The find() method returns a cursor that can be iterated over to retrieve all documents in the collection that match a specified query. You can also use the findOne() method to retrieve a single document that matches a specified query.

 

Here is an example of how you can use the find() method to read documents

const MongoClient = require('mongodb').MongoClient;

const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // find all documents where the price is greater than 700
  const query = { price: { $gt: 700 } };
  collection.find(query).toArray(function(err, documents) {
    console.log(documents);
    client.close();
  });
});

Here We created a query that finds all documents with a price greater than 700 and pass it to the find() method.

There is also a   findOne() method, it's almost similar to find() method, it just returns a single document that matches a specified query, instead of a cursor.

Update: MongoDB also supports updating existing documents. The update() method can be used to update one or multiple documents in a collection. The update() method takes two arguments: the first is the query that specifies which documents to update, and the second is the update operator that specifies how to update the documents. The update operator can be used to set new values for fields, increment existing values, and more.

Here is an example of how you can use the updateOne() method to update a single document 

const MongoClient = require('mongodb').MongoClient;

const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // specify the filter to find the document to update
  const filter = { name: "Smartphone" };
  // specify the update operation
  const update = { $set: { price: 900 } };
  collection.updateOne(filter, update, function(err, res) {
    console.log("Document updated");
    client.close();
  });
});

You can also use updateMany() method which  updates all the documents that match the filter instead of just one.

Delete: MongoDB also supports deleting existing documents. The deleteOne() method can be used to delete a single document that matches a specified query, and the deleteMany() method can be used to delete multiple documents that match a specified query.

Here is an example of how you can use the deleteOne() method to delete a single document

const MongoClient = require('mongodb').MongoClient;

const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // specify the filter to find the document to delete
  const filter = { name: "Smartphone" };
  collection.deleteOne(filter, function(err, res) {
    console.log("Document deleted");
    client.close();
  });
});

In addition to these basic CRUD operations, MongoDB also supports more advanced services such as aggregation, indexing, and map-reduce. These features can be used to perform more complex operations on the data in your collections for your application.

In conclusion, MongoDB is a powerful NoSQL database that supports a wide range of CRUD operations. Whether you're new to MongoDB or have been working with it for a while, understanding these basic operations is essential for working effectively with the database.

Shape

Drop your comment