You can delete array elements by index using the following two steps -
The first step is as follows -
db.yourCollectionName.update({}, {$unset : {"yourArrayFieldName.yourIndexValue" : 1 }});
The above syntax will be in "yourIndexValue" Place a null value at the position. After that you need to extract null values from array field to remove from array elements.
The second step is as follows -
db.yourCollectionName.update({}, {$pull : {"yourArrayFieldName" : null}});
To implement the syntax, let us create a collection with documents. The query to create a collection using documents 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 the documents in the 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" ] }
This is the query to delete array elements by index.
Step 1- Query as follows-
> db.removeArrayElementByItsIndexDemo.update({}, {$unset : {"InstructorSubject.2" : 1 }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Step 2-Query as follows-
> db.removeArrayElementByItsIndexDemo.update({}, {$pull : {"InstructorSubject" : null}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let’s check Whether the array element "Java" has been deleted. 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" ] }
View the sample output, the array element "Java" has been completely deleted.
The above is the detailed content of How to delete array elements by index in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!