How do you remove an array element by its index in MongoDB



To remove array element by its index in MongoDB, you can use unsetandpull operator. There are two steps to remove array elements from an array.The syntax for the same is as follows:

db.yourCollectionName.update({},{$unset:{"yourArrayListName.yourPosition":yourPositionValue}};
db.yourCollectionName.update({},{$pull:{"yourArrayListName":null}});

To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:

>db.removeArrayElements.insertOne({"StudentName":"Larry","StudentAge":23,"TechnicalSub
ject":["C","C++","Java","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ea4879c4643706aef56d2")
}

Display all documents from a collection with the help of find() method. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6ea4879c4643706aef56d2"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "TechnicalSubject" : [
      "C",
      "C++",
      "Java",
      "MongoDB"
   ]
}

Here is the query to remove array element by its index:

> db.removeArrayElements.update({},{$unset:{"TechnicalSubject.3":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.removeArrayElements.update({},{$pull:{"TechnicalSubject":null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Above, we have removed array element “MongoDB”, which is at index 3. Let us display documents from a collection. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6ea4879c4643706aef56d2"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "TechnicalSubject" : [
      "C",
      "C++",
      "Java"
   ]
}

Look at the above sample output, the index 3 i.e. position 4 has been removed from the array i.e. the element “MongoDB”.

Updated on: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements