[MongoDB] $pull and $pullAll for Removing Specific Elements from Array Fields

Tadashi Shigeoka ·  Tue, August 7, 2018

When you want to delete only specific elements from an Array field of a document in Mongoose, it seems good to use MongoDB’s $pull or $pullAll operators.

MongoDB | モンゴディービー

How to Use MongoDB $pull and $pullAll

$pull Sample Code

Assuming there’s data in an articles collection like this:

> db.articles.find()
{
  "_id": ObjectId("5b6d8b9e7e646a3119136780"),
  "editors": [
    ObjectId("5b6d8b9e7e646a311913677c"),
    ObjectId("5b6d8b9e7e646a311913677d"),
    ObjectId("5b6d8b9e7e646a311913677e"),
    ObjectId("5b6d8b9e7e646a311913677f")
  ]
}
{
  "_id" : ObjectId("5b6d8d417e646a3119136782"),
  "editors" : [
    ObjectId("5b6d8b9e7e646a311913677d"),
    ObjectId("5b6d8d417e646a3119136781")
  ]
}

Using the $pull operator to execute an update query:

var deletedUserId = ObjectId("5b6d8b9e7e646a311913677d")

db.articles.update(
  {},
  {
    $pull : {
      editors : deletedUserId
    }
  },
  {
    multi: true
  }
)

The deletedUserId element was removed from editors.

> db.articles.find()
{
  "_id": ObjectId("5b6d8b9e7e646a3119136780"),
  "editors": [
    ObjectId("5b6d8b9e7e646a311913677c"),
    ObjectId("5b6d8b9e7e646a311913677e"),
    ObjectId("5b6d8b9e7e646a311913677f")
  ]
}

$pullAll Sample Code

Continuing with using the $pullAll operator to execute an update query:

var deletedUserIds = [
  ObjectId("5b6d8b9e7e646a311913677e"),
  ObjectId("5b6d8b9e7e646a311913677f")
]

db.articles.update(
  {},
  {
    $pullAll: {
      editors: deletedUserIds
    }
  },
  {
    multi: true
  }
)

The deletedUserIds elements were removed from editors.

> db.articles.find()
{
  "_id": ObjectId("5b6d8b9e7e646a3119136780"),
  "editors": [
    ObjectId("5b6d8b9e7e646a311913677c")
  ]
}
{
  "_id": ObjectId("5b6d8d417e646a3119136782"),
  "editors": [
    ObjectId("5b6d8b9e7e646a311913677d"),
    ObjectId("5b6d8d417e646a3119136781")
  ]
}

What Are the Use Cases for $pull and $pullAll?

Use cases for MongoDB’s $pull and $pullAll are when you want to clean up fields where references like articles.editors are stored when physically deleting editors data due to user withdrawal.

That’s all from the Gemba where I want to remove specific elements from MongoDB Array fields.