DEV Community

Cover image for MongoDB with Node.js, CRUD Operation
Suresh Pal Pranta
Suresh Pal Pranta

Posted on • Edited on

MongoDB with Node.js, CRUD Operation

MongoDB

MongoDB is a no-SQL database. It represents data as JSON documents. It maintains some collections where data are stored as documents. It is much more flexible than an SQL database since we can store documents of different formats in the same collection. One more advantage is that we can use JavaScript as our query language.

Node.js

Node.js is a non-blocking JavaScript runtime environment. Client-side JavaScript codes are executed in the browser. Node.js is used to run JavaScript code outside the browser.

Node.js vs JavaScript

JavaScript is a programming language that is used for front-end development while Node.js is used for server-side development. JavaScript codes are executed in the browser normally. With the help of Node.js, we can run JS code outside the browser.

Connecting MongoDB with node.js server

  1. Go to MongoDB atlas and create an account.
  2. Create a cluster.
  3. Go to database access and create a user.
  4. Allow network access.
  5. Click on connect and then connect your application.

Replace the username and password carefully in the connection string of your cluster with valid username and password.

const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://<username>:<password>@cluster0.yxq3j.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
Enter fullscreen mode Exit fullscreen mode
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
  const productsCollection = client.db("testDB").collection("products");
  console.log(“Database connected successfully!”);  
  // client.close();
});
Enter fullscreen mode Exit fullscreen mode

Create or Insert Operation

We can insert a single document or multiple documents into a collection. To insert a single document we need to use the insertOne() method.

const product = {
      category: "Shirt",
      price: 200
}
const result = productsCollection.insertOne(product);
Enter fullscreen mode Exit fullscreen mode

If we want to insert many documents then we need to use the insertMany() method.

const docs = [
      { name: "apple", price: 30 },
      { name: "orange", price: 50 }
];
const result = foods.insertMany(docs);

Enter fullscreen mode Exit fullscreen mode

Read or Find Operation

To find a document from the database we need to use findOne() method and we can pass query and options as parameter of this method to find our desired document.

// Query for a mobile that has the title 'Redmi Note 4'
const query = { title: "Redmi Note 4" };
const mobile = movies.findOne(query);
Enter fullscreen mode Exit fullscreen mode

To find multiple documents from a collections we need to use find() method. This method will return a cursor and we can apply cursor methods next(), toArray(), forEach().

const cursor = products.find({});
const products = cursor.toArray();
Enter fullscreen mode Exit fullscreen mode

Update Operation

To update a single document we need to use updateOne() method. In this method we can pass three parameters filter, updateDoc and options which is optional.

// create a filter for a product to update
const filter = { name: "Redmi Note 4" };
// create a new document if no documents match the filter
const options = { upsert: true };
// updating a document that sets the price of the mobile
const updateDoc = {
      $set: {
        price: 20000
      },
};
const result = movies.updateOne(filter, updateDoc, options);
Enter fullscreen mode Exit fullscreen mode

To update multiple documents we need to use updateMany() method.

Delete Operation

We can delete a single document or multiple documents if we want. To delete a single document we need to use deleteOne() method and passing a query parameter to this method we will specify which documents we want to delete.

const query = { title: "Redmi9" };
const result = mobileCollection.deleteOne(query);

Enter fullscreen mode Exit fullscreen mode

To delete multiple documents we need to use deleteMany() method.

Top comments (0)