How to Pull Item from an Array in Mongoose ?
Last Updated :
17 May, 2024
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
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
Similar Reads
How to Push Item From an Array in Mongoose? Mongoose, an Object Data Modeling (ODM) library for Node.js and MongoDB, makes database interactions easier through a comprehensive API. One of the most frequent operations that developers execute using Mongoose is adding an item to an array of a document. In this article, we will discuss the differ
6 min read
How to Delete a Field From a Document in Mongoose? Databases are an essential component of web development. They are used for storing and managing data. MongoDB is a widely used NoSQL database. A Mongoose is a tool designed to simplify interactions with MongoDB databases in Node.js applications, making it an elegant MongoDB object modeling solution.
5 min read
How to Creating Mongoose Schema with an Array of ObjectID In Mongoose, a powerful MongoDB object modeling tool for Node.js, schemas define the structure of documents within a collection. Sometimes, you may need to create a schema with an array of ObjectIDs to represent relationships between documents in different collections. This article will explain how
4 min read
How to Retrieve only the Queried Element in an Object Array in MongoDB Collection In MongoDB, retrieving specific elements from an object array within a document is a common requirement, especially when dealing with complex data structures. MongoDB provides powerful query operators to filter and retrieve only the elements that match certain criteria within an array. This capabili
4 min read
Mongoose Document.prototype.$isEmpty() API The Document API.prototype.$isEmpty() method of the Mongoose API is used on the Document model. It allows us verify whether any field in the document is empty or not. If any specific field in the document object is not having value, then the isEmpty() method will return true else it will return fals
3 min read