Remove values from a matrix like document in MongoDB

To remove values from a matrix-like document in MongoDB, use the $pull operator with dot notation to target specific elements within nested arrays. This operator removes all instances of a specified value from an array field.

Syntax

db.collection.update(
    { query },
    { $pull: { "arrayMatrix.index": value } }
);

Sample Data

Let's create a collection with a matrix-like document ?

db.demo632.insertOne({
    "arrayMatrix": [
        [10, 20],
        [10, 20],
        [10, 20],
        [10, 20],
        [10, 20],
        [10, 20]
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e9b27b46c954c74be91e6c0")
}

Display the document to verify the structure ?

db.demo632.find().pretty();
{
    "_id": ObjectId("5e9b27b46c954c74be91e6c0"),
    "arrayMatrix": [
        [10, 20],
        [10, 20],
        [10, 20],
        [10, 20],
        [10, 20],
        [10, 20]
    ]
}

Example: Remove Value from Matrix Elements

Remove the value 20 from all sub-arrays in the matrix ?

db.demo632.update(
    {},
    {
        "$pull": {
            "arrayMatrix.0": 20,
            "arrayMatrix.1": 20,
            "arrayMatrix.2": 20,
            "arrayMatrix.3": 20,
            "arrayMatrix.4": 20,
            "arrayMatrix.5": 20
        }
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo632.find().pretty();
{
    "_id": ObjectId("5e9b27b46c954c74be91e6c0"),
    "arrayMatrix": [
        [10],
        [10],
        [10],
        [10],
        [10],
        [10]
    ]
}

Key Points

  • Use dot notation "arrayMatrix.index" to target specific sub-arrays within the matrix.
  • $pull removes all occurrences of the specified value from each targeted array.
  • Each sub-array index must be specified individually in the $pull operation.

Conclusion

The $pull operator with dot notation effectively removes specific values from matrix-like documents in MongoDB. This approach allows precise control over which elements to remove from nested array structures.

Updated on: 2026-03-15T03:13:12+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements