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

  • $pull removes all array elements that match the specified condition
  • $mod: [2, 0] identifies numbers where number % 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.

Updated on: 2026-03-15T01:11:41+05:30

634 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements