Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to pull even numbers from an array in MongoDB?
To pull even numbers from an array in MongoDB, use the $pull operator combined with the $mod operator. The $mod operator performs modulo division to identify even numbers (remainder 0 when divided by 2).
Syntax
db.collection.updateMany(
{},
{ $pull: { "arrayField": { $mod: [2, 0] } } }
);
Sample Data
db.pullEvenNumbersDemo.insertOne({
"AllNumbers": [101, 102, 104, 106, 108, 109, 110, 112, 14, 17, 18, 21]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd45b072cba06f46efe9eea")
}
Display Initial Data
db.pullEvenNumbersDemo.find().pretty();
{
"_id": ObjectId("5cd45b072cba06f46efe9eea"),
"AllNumbers": [
101, 102, 104, 106, 108, 109, 110, 112, 14, 17, 18, 21
]
}
Example: Pull Even Numbers
Remove all even numbers from the AllNumbers array ?
db.pullEvenNumbersDemo.updateMany(
{},
{ $pull: { "AllNumbers": { $mod: [2, 0] } } }
);
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}
Verify Result
db.pullEvenNumbersDemo.find().pretty();
{
"_id": ObjectId("5cd45b072cba06f46efe9eea"),
"AllNumbers": [101, 109, 17, 21]
}
How It Works
-
$pullremoves all array elements that match the specified condition -
$mod: [2, 0]identifies numbers wherenumber % 2 === 0(even numbers) - The operation removes: 102, 104, 106, 108, 110, 112, 14, 18
- Only odd numbers remain: 101, 109, 17, 21
Conclusion
Use $pull with $mod: [2, 0] to efficiently remove even numbers from MongoDB arrays. This approach leverages MongoDB's modulo operator to identify and remove elements based on mathematical conditions.
Advertisements
