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

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

Similar Reads

Steps to Create the Application

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

Using $pull Operator

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

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....

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....

Using the $pop Operator

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

Using Custom Logic

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

Contact Us