Remove values from a matrix like document in MongoDB


To remove values from a matrix, use $pull in MongoDB. Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo632.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e9b27b46c954c74be91e6c0"),
   "arrayMatrix" : [
      [
         10,
         20
      ],
      [
         10,
         20
      ],
      [
         10,
         20
      ],
      [
         10,
         20
      ],
      [
         10,
         20
      ],
      [
         10,
         20
      ]
   ]
}

Following is the query to remove values from a matrix like document in MongoDB −

> 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 })

Display all documents from a collection with the help of find() method −

> db.demo632.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e9b27b46c954c74be91e6c0"),
   "arrayMatrix" : [
      [
         10
      ],
      [
         10
      ],
      [
         10
      ],
      [
         10
      ],
      [
         10
      ],
      [
         10
      ]
   ]
}

Updated on: 12-May-2020

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements