How to Pull Item from an Array in Mongoose ?

In Mongoose, pulling an item from an array can be done using several methods. To pull an item from an array, you can use the $pull operator along with the updateOne() or updateMany() method.

We will discuss the different methods to pull items from an array in Mongoose

Table of Content

  • Using $pull Operator
  • Pull Based on a Condition
  • Pull from Nested Arrays
  • Using the $pop Operator

Steps to Create the Application

Step 1: Make a folder named ‘mongodb-example’ and navigate to it using this command.

mkdir mongodb-example
cd mongodb-example

Step 2: Install modules as per requirements.

npm install express  mongoose  

Project Structure

Project Structure

Updated Dependencies in your package.json file

 "dependencies": {
    "express": "^4.19.2",
    "mongoose": "^8.3.4"
  }

Example: This code is of server.js file which is same for all approaches example code and ‘app.js’ is inserting sample document for performing all example code.

JavaScript
// Filename - Server.js

const mongoose = require('mongoose')
const DB_URI = 'XXXX-XXX'

function dbConnection() {
    mongoose.connect(DB_URI)
    console.log('Database connected successfully.')
}

const productSchema = new mongoose.Schema({
    name: String,
    price: Number,
    categories: [String],
    reviews: [{
        reviewer: String,
        rating: Number,
        comment: String
    }]
});

const Product = mongoose.model('Product', productSchema);
module.exports = {
    dbConnection,
    Product
}
JavaScript
// app.js 

const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')

dbConnection(); // connecting to database 

async function inserting() {
    const newProduct = new Product({
        name: 'Laptop',
        price: 999.99,
        categories: ['Electronics', 'Computers'],
        reviews: [
            { reviewer: 'sandy', rating: 5, comment: 'Great laptop!' },
            { reviewer: 'nakul', rating: 4, comment: 'Good value for money.' },
            { reviewer: 'jatin', rating: 3, comment: 'Loving Product.' },
            { reviewer: 'mukesh', rating: 2, comment: ' Decent.' },
            { reviewer: 'mohan', rating: 0, comment: 'no value.' }
        ]
    });

    await newProduct.save()
    console.log('Item inserted successfully.')
}

inserting()

// server listening 
app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`)
})

Output:

MongoDB Output

Using $pull Operator

To remove a specific value from an array, employ the $pull operator with the targeted ( to be removed ) value.

Example:

JavaScript
// Filename - app.js

const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')

dbConnection(); // connecting to database 

async function pulling(productId, categoryToRemove) {
    const result = await Product.updateOne(
        { _id: productId },
        { $pull: { categories: categoryToRemove } });
    console.log('Category removed:', result);
}

pulling('664491772960d488ab55a620', 'Electronics')

// server listening 
app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`)
})

Output:

$Pull Operator Output

Pull Based on a Condition

Here you have one or more queries and you remove elements based on that queries by any method like $pull operator or custom logic.

Example:

JavaScript
// Filename - app.js

const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')

dbConnection(); // connecting to database 

async function pulling(productId) {
    const result = await Product.updateOne(
        { _id: productId },
        { $pull: { reviews: { rating: { $lt: 4 } } } },
    );
    console.log('Reviews removed:', result);
}

pulling('664491772960d488ab55a620')

// server listening 
app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`)
})

Output:

$Pull On Condition Output

Pull from Nested Arrays

Pulling from nested arrays involves using the $pull operator with dot notation to specify the nested array path. You can also remove elements based on conditions within the nested array.

Example:

JavaScript
// app.js 

const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')

dbConnection(); // connecting to database 

async function pulling(productId, reviewer) {
    const result = await Product.findByIdAndUpdate(productId,
        { $pull: { reviews: { reviewer } } });
    console.log('Review by reviewer removed:', result);
}

pulling('664491772960d488ab55a620', 'nakul')

// server listening 
app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`)
})

Output:

$Pull from Nested Array Output

Using the $pop Operator

The $pop operator removes the first(-1) or last (1 ) element from an array.

Example:

JavaScript
// Filename - app.js

const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')

dbConnection(); // connecting to database 

async function pulling(productId ) {
    const result = await Product.findByIdAndUpdate(productId,
        { reviews: { $pop: { reviewer: -1 } } });
    console.log('Review by reviewer removed:', result);
}

pulling('664491772960d488ab55a620' )

// server listening 
app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`)
})

Output:

$Pop Operator Output

Using Custom Logic

It involves manually retrieving the document, modifying the array using JavaScript, and then saving the modified document to the database.

Example:

JavaScript
// Filename - app.js 

const express = require('express')
const app = express();
const PORT = 8000;
const { Product, dbConnection } = require('./server')

dbConnection(); // connecting to database 

async function pulling(productId, elementToRemove) {
    const product = await Product.findById(productId);
    product.reviews = product.reviews.filter(item => item.reviewer !== elementToRemove);
    await product.save();
    console.log('Review by reviewer removed:', product);
}

pulling('66449c28c1c05b5eccf8071a', 'jatin')

// server listening 
app.listen(PORT, () => {
    console.log(`Server is running on ${PORT}`)
})

Output:

Custom Logic Output



Contact Us