Working with MongoDB in Node

MongoDB is a popular NoSQL database that is often used with Node.js for building scalable and flexible applications.

In this tutorial, you will learn CRUD Operations, Quering Data, Aggregations and more in MongoDB using Node.

Setting Up MongoDB and the Node.js Driver

  1. To get started, you'll need to install MongoDB and the official Node.js driver for MongoDB mongodb
npm install mongodb

Connecting to MongoDB

  1. To connect to MongoDB, create a connection using the MongoClient and the connection string.
const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

async function connectToMongo() {
    await client.connect();
    console.log('Connected to MongoDB');
}

connectToMongo();
    

CRUD (Create Read Update and Delete) Operations

  1. MongoDB supports four primary CRUD (Create, Read, Update, Delete) operations.
  2. To insert data into a MongoDB collection, you can use the insertOne or insertMany methods.
async function insertData() {
    const db = client.db('mydatabase');
    const collection = db.collection('mycollection');
    
    const data = { name: 'John', age: 30 };
    const result = await collection.insertOne(data);
    
    console.log('Inserted data:', result.ops[0]);
  }
  
  insertData();
  
  • To query data from a collection, use the find method.
  • async function queryData() {
    const db = client.db('mydatabase');
    const collection = db.collection('mycollection');
    
    const query = { name: 'Alice' };
    
    const data = await collection.find(query).toArray();
    
    console.log('Queried data:', data);
    }
    
    queryData();
    
  • To update data, use the updateOne or updateMany methods.
  • async function updateData() {
    const db = client.db('mydatabase');
    const collection = db.collection('mycollection');
    
    const query = { name: 'Alice' };
    const update = { $set: { age: 26 } };
    
    const result = await collection.updateOne(query, update);
    
    console.log('Updated data:', result.modifiedCount);
    }
    
    updateData();
      
  • To delete data, use the deleteOne or deleteMany methods.
  • async function deleteData() {
    const db = client.db('mydatabase');
    const collection = db.collection('mycollection');
    
    const query = { name: 'Alice' };
    
    const result = await collection.deleteOne(query);
    
    console.log('Deleted data:', result.deletedCount);
    }
    
    deleteData();
      

    Indexing

    1. Indexes can be created to improve the query performance.
    2. For example, creating an index on the 'name' field
    async function createIndex() {
    const db = client.db('mydatabase');
    const collection = db.collection('mycollection');
    
    const result = await collection.createIndex({ name: 1 });
    
    console.log('Created index:', result);
    }
    
    createIndex();
      

    Aggregation

    1. MongoDB supports aggregation pipelines to perform complex operations on data.
    async function aggregationExample() {
        const db = client.db('mydatabase');
        const collection = db.collection('mycollection');
        
        const pipeline = [
          { $match: { age: { $gte: 25 } } },
          { $group: { _id: null, total: { $sum: 1 } } },
        ];
        
        const result = await collection.aggregate(pipeline).toArray();
        
        console.log('Aggregation result:', result);
      }
      
      aggregationExample();
      

    Error Handling

    1. Always handle errors when working with MongoDB to ensure robust applications.
    async function handleErrorExample() {
    const db = client.db('mydatabase');
    const collection = db.collection('mycollection');
    
    try {
        // MongoDB operations
    } catch (error) {
        console.error('MongoDB error:', error);
    }
    }
    
    handleErrorExample();