How to Remove an Element from an Array in MongoDB?

To remove an element from an Array in MongoDB, you can use the $pull operator. The $pull operator in MongoDB is used to remove a specific element from an array based on a condition or a value.

The $pull operator is used with the update() or updateMany() methods and it modifies the values of the specified field array by removing the elements that match the specified value or condition.

The syntax of the $pull operator is as follows:

db.collection.update(
   <query>,
   { $pull: { <field1>: <value1 | condition1>, <field2>: <value2 | condition2>, ... } }
)

The <query> is the query that specifies what all documents should be selected, the <field> is the name of the array field and the <value> is the value that you want to remove from the array.

The <condition> can be any valid MongoDB condition based on which you want to remove elements from the array.

Let’s take a few examples and try to implement it. So without any further ado, let’s get started.


Remove an element from the array by value

Let’s create a collection store whose each document has an array field named items:

db.store.insertMany([
    { "_id" : 1, "items" : [ "books", "movies", "music" ] },
    { "_id" : 2, "items" : [ "books", "movies" ] },
    { "_id" : 3, "items" : [ "books" ] }
])

Now, we want to remove the item “music” from the first document i.e. document with _id=1.

To achieve that we can directly pass the value “music” to the $pull operator i.e. { $pull: { items: "music" } }:

See the following example:

db.store.update(
   { _id: 1 },
   { $pull: { items: "music" } }
)

Now, if you run the db.store.find() query, it will give you the modified result as follows:

{ _id: 1, items: [ 'books', 'movies' ] }
{ _id: 2, items: [ 'books', 'movies' ] }
{ _id: 3, items: [ 'books' ] }

As you can see from the above output, the value “music” is removed from the document having _id=1.


Removing a value from all documents’ array:

You can also remove a given value from the specified array of all the documents.

For that, you have to pass the <query> as an empty document {} to the update() method and pass { multi: true } as a third parameter to it so that the given value is removed from the array of all documents.

The following example removes the item “books” from the items array of all documents:

db.store.update(
   { },
   { $pull: { items: "books" } },
   { multi: true}
)

Run the db.store.find() command to get the modified result:

{ _id: 1, items: [ 'movies' ] }
{ _id: 2, items: [ 'movies' ] }
{ _id: 3, items: [ ] }

As you can see from the above output, the item “books” is removed from the items array of all the documents.


Remove Array Elements that Match a Specified Condition

You can also remove single or multiple elements from the array using the $pull operator that matches the specified condition.

Let’s create a collection profile and insert a few documents into it:

db.profile.insertMany([
{
  _id: 1, user: 'user1', score: [ 1, 2, 5, 7, 8 ]
},
{
  _id: 2, user: 'user2', score: [ 1, 2, 1, 5, 9 ]
},
{
  _id: 3, user: 'user3', score: [ 5, 6, 5, 8, 10 ]
  
}
])

Now we want to remove those score values from the score array of each document which are lower than 5.

To accomplish that we can use the $lt operator with the $pull operator. The $lt operator selects those documents/values which are less than(<) the specified value.

The following example removes those score values from the score array of each document which are less than 5:

db.profile.updateMany(
  { },
  { $pull: { score : { $lt : 5} } },
)

Now run the db.profile.find() command. After execution, it will give you the following output:

{
  _id: 1, 
  user: 'user1',
  score: [ 5, 7, 8 ]
}
{
  _id: 2,
  user: 'user2',
  score: [ 5, 9 ]
}
{
  _id: 3,
  user: 'user3',
  score: [ 5, 6, 5, 8, 10 ]
}

As you can see from the above output, values less than 5 are deleted from the score array of each document.


Remove Items from an Array of Documents

Let’s create a students collection with the following documents:

db.students.insertMany([
  {
    _id: 1,
    name: "student 1",
    subjects: [
      { subject: "Math", marks: 87 },
      { subject: "Science", marks: 53 }
    ]
  },
  {
    _id: 2,
    name: "student 2",
    subjects: [
      { subject: "Math", marks: 48 },
      { subject: "Science", marks: 92 }
    ]
  }
])

Each student has a subjects field. The subjects field is an array of documents where each document contains the information of a subject.

We want to remove those documents from the subjects array whose marks are less than 60.

The following query removes those documents from the subjects array that has marks lower than 60:

db.students.updateMany(
  { },
  { $pull: { subjects: { marks: { $lt: 60 } } } }
)

Now, run the db.students.find() command to get the modified result. It will give you the following result:

{
  _id: 1,
  name: 'student 1',
  subjects: [
    {
      subject: 'Math',
      marks: 87
    }
  ]
}
{
  _id: 2,
  name: 'student 2',
  subjects: [
    {
      subject: 'Science',
      marks: 92
    }
  ]
}

As you can see from the above output, those documents which have marks lower than 60 are deleted from the subjects array of each student.


Conclusion

In this article, we learned how we can remove single or multiple items from an array in MongoDB.

In summary, if you want to remove single or multiple elements from a plain or a nested array in MongoDB, you can use the $pull operator.

The $pull operator in MongoDB is used to remove a given item from an existing array. It can also remove items that match the specified condition.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts