How to remove an array element by its index in MongoDB?

MongoDBDatabaseBig Data Analytics

You can remove an array element by its index using the following two steps −

The first step is as follows −

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

The above syntax will put a null value at the location of ‘yourIndexValue’. After that, you need to pull the null value from array filed to remove from an array element.

The second step is as follows −

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

To implement the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.removeArrayElementByItsIndexDemo.insertOne({"InstructorName":"David",
   "InstructorAge":28,"InstructorSubject":["MongoDB","MySQL","Java","SQL Server","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8abbfc6cea1f28b7aa0803")
}

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

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

The following is the output −

{
   "_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"),
   "InstructorName" : "David",
   "InstructorAge" : 28,
   "InstructorSubject" : [
      "MongoDB",
      "MySQL",
      "Java",
      "SQL Server",
      "PL/SQL"
   ]
}

Here is the query to remove an array element by its index.

Step 1 − The query is as follows −

> db.removeArrayElementByItsIndexDemo.update({}, {$unset : {"InstructorSubject.2" : 1 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Step 2 − The query is as follows −

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

Let us check the array element “Java” has been removed or not. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"),
   "InstructorName" : "David",
   "InstructorAge" : 28,
   "InstructorSubject" : [
      "MongoDB",
      "MySQL",
      "SQL Server",
      "PL/SQL"
   ]
}

Look at the sample output, the array element “Java” has been removed completely.

raja
Published on 29-Mar-2019 15:05:08
Advertisements