Use the $pull operator to pull array element from a collection. Let us first create a collection with documents −
> db.pullElementFromAnArrayDemo.insertOne( ... { ... "StudentScores":[89,56,78,90] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd0104a588d4a6447b2e063") }
Following is the query to display all documents from a collection with the help of find() method −
> db.pullElementFromAnArrayDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd0104a588d4a6447b2e063"), "StudentScores" : [ 89, 56, 78, 90 ] }
Following is the query to pull array element from a collection. Here, we are removing element 78 −
> db.pullElementFromAnArrayDemo.update({},{ $pull: { StudentScores: 78 } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.pullElementFromAnArrayDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd0104a588d4a6447b2e063"), "StudentScores" : [ 89, 56, 90 ] }