How to remove array element in MongoDB?

MongoDBDatabaseBig Data Analytics

To remove array element in MongoDB, you can use $pull and $in operator. The syntax is as follows:

db.yourCollectionName.update({},
   {$pull:{yourFirstArrayName:{$in:["yourValue"]},yourSecondArrayName:"yourValue"}},
   {multi:true}
);

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

>db.removeArrayElement.insertOne({"StudentName":"Larry","StudentCoreSubject":["MongoD
B","MySQL","SQL Server","Java"],"StudentFavouriteTeacher":["John","Marry","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ec9c46fd07954a4890688")
}

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

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

The following is the output:

{
   "_id" : ObjectId("5c6ec9c46fd07954a4890688"),
   "StudentName" : "Larry",
   "StudentCoreSubject" : [
      "MongoDB",
      "MySQL",
      "SQL Server",
      "Java"
   ],
   "StudentFavouriteTeacher" : [
      "John",
      "Marry",
      "Carol"
   ]
}

Here is the query to remove array element in MongoDB:

> db.removeArrayElement.update({},
... {$pull:{StudentCoreSubject:{$in:["Java"]},StudentFavouriteTeacher:"Marry"}},
... {multi:true}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

We have “Java” element from first array(“StudentCoreSubject”) above and the second value “Marry” element from second array(“StudentFavouriteTeacher”).

Let us display documents from a collection once again to check the two elements have been removed or not. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6ec9c46fd07954a4890688"),
   "StudentName" : "Larry",
   "StudentCoreSubject" : [
      "MongoDB",
      "MySQL",
      "SQL Server"
   ],
   "StudentFavouriteTeacher" : [
      "John",
      "Carol"
   ]
}

Look at the above sample output, there is no “Java” element in the first array(“StudentCoreSubject”) and no “Marry” element in second array(“StudentFavouriteTeacher”). Therefore, we have successfully removed them from the collection.

raja
Published on 18-Mar-2019 11:51:18
Advertisements