MongoDB remove an element from the array

In this MongoDB tutorial, we are going to learn “MongoDB remove an element from an array”. We will cover this topic with different operations and examples. These are the following topics that we are going to cover in this tutorial:

  • MongoDB remove an element from the array query
  • MongoDB remove an element from the array by id
  • MongoDB remove an element from the array index
  • MongoDB remove the last element from the array
  • MongoDB remove an element from a nested array
  • MongoDB remove multiple elements from the array

MongoDB remove an element from the array query

MongoDB provides the following operators to remove an element from an array. The operators are:

  • $pull
  • $pullAll
  • $pop

Now, we will learn all these operators in detail with examples.

The $pull operator: The $pull operator removes an element from an existing array that matches a specified condition.

Assume, we have a collection called product with the following documents:

db.product.insertMany([
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "XL", "XXL" ] },
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "L", "XL" ] },
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "XS", "S", "M", "L", "XL" ] }
])

We can remove an element from the array using the following query:

db.products.update( 
  { _id: 1 }, 
  { $pull: { sizes: "XXL" } } 
)

Here, we have used the update() method and defined the $pull operator to remove an element XXL where _id is 1. After that, you can use the find() method to retrieve all the documents.

db.product.find()
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "XL" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "XS", "S", "M", "L", "XL" ] }

We have successfully removed an element from the array.

The $pullAll operator: The $pullAll operator removes all the elements from the defined array.

Assume, we have a collection called demo with the following documents:

db.demo.insertMany([
{ "_id" : 1, "bar" : [ 1, 8, 2, 3, 8, 7, 1 ] },
{ "_id" : 2, "bar" : [ 0, 1, 8, 17, 18, 8 ] },
{ "_id" : 3, "bar" : [ 15, 11, 8, 0, 1, 3 ] }
])

Now, use the following query to remove all values of 8 from the array where _id is 1.

db.demo.update( 
  { _id: 1 }, 
  { $pullAll: { bar: [ 8 ] } } 
)

We can verify this by checking the collection using the find() method.

db.demo.find()
{ "_id" : 1, "bar" : [ 1, 2, 3, 7, 1 ] }
{ "_id" : 2, "bar" : [ 0, 1, 8, 17, 18, 8 ] }
{ "_id" : 3, "bar" : [ 15, 11, 8, 0, 1, 3 ] }

We have successfully removed element 8 from the array in document 1.

Note

The $pullAll operator is similar to $pull. The difference is that $pullAll removes elements that match the listed values. And, the $pull operator remove values by specifying a query.

The $pop operator: The $pop operator is used to remove the first or last element of an array. It provides a value of -1 to remove the first element and 1 to remove the last element of an array.

Assume, we have a collection called test with the following documents:

db.test.insertMany([
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "M", "L", "XL" ] },
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "M", "L", "XL" ] },
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "S", "M", "L" ] }
])

The following query will remove the first element of the array in document 3.

db.test.update( 
  { _id: 3 }, 
  { $pop: { sizes: -1 } } 
)

We can verify this by checking the collection using the find() method.

db.test.find()
{ "_id" : 1, "prod" : "Bat", "sizes" : [ "M", "L", "XL" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "M", "L", "XL" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "M", "L" ] }

We have successfully removed the first element from the array in document 3.

MongoDB remove an element from the array by id

In this topic, we will learn to remove an element from the array by id. Here, the array by id means removing a particular id array element. We will use the $pull operator in the update() method to remove the element from the array. Let us understand with the help of an example:

Example:

The subsequent documents were inserted into the store collection.

db.store.insertMany([
{
   _id: 1,
   fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
   vegetables: [ "carrots", "celery", "squash", "carrots" ],
   city: ["USA", "UK", "Australia"]
},
{
   _id: 2,
   fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
   vegetables: [ "broccoli", "zucchini", "carrots", "onions" ],
   city: ["Canada", "United States", "New Zealand"]
}
])

After that, we will apply the following query to remove an element from the array.

db.store.update(
    { _id: 2 },
    { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } }
)

Here, we have specified id 2 so in id 2 the $pull operator will remove apples and oranges from the array fruits and remove carrots from the array vegetables.

MongoDB remove an element from the array
MongoDB remove an element from the array

We can verify this by checking the collection using the find() method.

db.store.find()
{
   _id: 1,
   fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
   vegetables: [ "carrots", "celery", "squash", "carrots" ],
   city: ["USA", "UK", "Australia"]
}
{
   _id: 2,
   fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
   vegetables: [ "broccoli", "zucchini", "carrots", "onions" ],
   city: ["Canada", "United States", "New Zealand"]
}

Read MongoDB find last inserted document

MongoDB remove an element from the array index

There is no exact way of pulling or removing an element by the array index. This is an open issue http://jira.mongodb.org/browse/SERVER-1014

The loophole is using the $unset and then $pull:

db.list.update({}, {$unset : {"interests.3" : 1 }}) 
db.list.update({}, {$pull : {"interests" : null}})

Update: This approach is not atomic and can cause some type of conditions if other clients read and/or write between the two operations. If we want the operation to be atomic, we could:

  • Read the document from the database
  • Update the document and remove the item in the array
  • Replace the document in the database. 

If you use the above approach to remove an array element by its index then this way it works.

Example:

The following document was inserted into the info collection.

db.info.insert(
{
   "InstructorName" : "Jack",
   "InstructorAge" : 25,
   "InstructorSubject" : [
      "MongoDB",
      "MySQL",
      "Java",
      "SQL Server",
      "PL/SQL"
   ]
}
)

Now, we will apply two queries to remove an array element by its index:

Step 1: Apply the $unset operator to put a null value at the location of “YourIndexValue”.

db.yourCollectionName.update(
       { }, 
       { $unset : {"yourArrayFieldName.yourIndexValue": 1 }}
)

Let us execute the below query:

db.info.update(
     { }, 
     {$unset : {"InstructorSubject.2" : 1 }}
)

Step 2: The $pull operator is used to pull the null value from the array to remove it from an array element.

db.yourCollectionName.update(
      { }, 
      { $pull : {"yourArrayFieldName": null }}
)

Let us execute the below query:

db.info.update(
    { }, 
    { $pull : {"InstructorSubject": null }} 
)

After that, check the array element “Java” has been removed or not. The query is as follows:

db.info.find().pretty()
MongoDB remove an element from the array index
MongoDB remove an element from the array index

Look at the output, we have successfully removed the array element “Java”.

Read MongoDB order by date

MongoDB remove the last element from the array

In this topic, you will learn to remove the last element from the array. For that, we will use the $pop operator to remove the last element from the array. It provides a value -1 to remove the first element and 1 to remove the last element of an array.

So here, we will use 1 to remove the last element of an array. Let’s understand with the help of an example.

Example:

The following documents were inserted into the store collection.

db.store.insertMany([
{
   _id: 1,
   fruits: [ "apples", "pears", "oranges", "grapes" ],
   vegetables: [ "carrots", "celery", "squash", "carrots" ]
},
{
   _id: 2,
   fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
   vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
])

Now, we will apply the below query to remove the last element from the array.

db.store.update(   
       { _id: 1},   
       { $pop: { fruits: 1 } } 
)

Here, we have applied the $pop operator with value 1 to remove the last element from the document 1 array fruits.

After that, check the array element to retrieve all the documents by using the find() method.

db.store.find()
MongoDB remove the last element from the array
MongoDB remove the last element from the array

We have successfully removed the last array element “grapes” from the fruits field in document 1.

Read MongoDB find string contains

MongoDB remove an element from a nested array

In this topic, we will learn to remove an element from a nested array. We will use the $pull operator to remove the element from a nested array. Let us understand with the help of an example.

Example:

The following documents were inserted into the inventory collection.

db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
])

Now, we will apply the below query to remove an element from a nested array.

db.inventory.update(   
      {"_id": ObjectId("6177dac20780fa24a6ee9014")},       
      { $pull: { "instock": { warehouse: "C" }}} 
)

After that, retrieve all the documents using the find() method.

db.inventory.find()
MongoDB remove an element from a nested array
MongoDB remove an element from a nested array

We have successfully removed the element from the nested array.

Read MongoDB find multiple values

MongoDB remove multiple elements from the array

In this topic, you will learn to remove multiple elements from the array. We will use the $pullAll operator to remove multiple elements from the array. Let us understand with the help of an example.

Example:

The following documents were inserted into the student collection.

db.student.insertMany([
{
    "_id": 1,
    "sem": 1,
    "subjects": [ "phys", "chem", "maths", "gkn", "stat", "astro"],
    "achieve" : [ 70, 87, 90, 80, 66, 82]
},
{
    "_id": 2,
    "sem": 1,
    "subjects": [ "phys", "chem", "maths", "gkn", "stat", "astro"],
    "achieve" : [ 72, 87, 90, 90, 66, 82, 87]
}
])

Now, we will apply the below query to remove multiple elements from the array achieve field in id 1.

db.student.update( 
      { "_id": 2 }, 
      { $pullAll: { "achieve": [72,87,90] }} 
)
MongoDB remove multiple elements from the array
MongoDB remove multiple elements from the array

We have successfully removed multiple elements from the array achieve field where id is 2.

You may also like the following MongoDB tutorials:

So, In this tutorial, we have learned “MongoDB remove an element from the array” using different approaches with examples. These are the following topics that we covered in this tutorial:

  • MongoDB remove an element from the array query
  • MongoDB remove an element from the array by id
  • MongoDB remove an element from the array index
  • MongoDB remove the last element from the array
  • MongoDB remove an element from a nested array
  • MongoDB remove multiple elements from the array