Clearing items in a nested MongoDB array?


To clear items in a nested array, use the $set operator. Let us first create a collection. Following is the query to create a collection with documents

> db.clearingItemsInNestedArrayDemo.insertOne( {
...
...    "StudentName" : "John",
...    "StudentDetails" : [
...       {
...          "ProjectName" : "Online Banking",
...          "ProjectDetails" : [
...             {
...                "TechnologyUsed" : "Java",
...                "TeamSize":5
...             },
...
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9930b4330fd0aa0d2fe4ce")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9930b4330fd0aa0d2fe4ce"),
   "StudentName" : "John",
   "StudentDetails" : [
      {
         "ProjectName" : "Online Banking",
         "ProjectDetails" : [
            {
               "TechnologyUsed" : "Java",
               "TeamSize" : 5
            }
         ]
      }
   ]
}

Following is the query to clear items in a nested array

> db.clearingItemsInNestedArrayDemo.update({"StudentName": "John"}, {"$set": {"StudentDetails": []}});
Updated 1 existing record(s) in 4ms
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now check the documents from the collection once again to verify that the items have been cleared from the nested array or not. Following is the query

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

This will produce the following output

{
   "_id" : ObjectId("5c9930b4330fd0aa0d2fe4ce"),
   "StudentName" : "John",
   "StudentDetails" : [ ]
}

Updated on: 30-Jul-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements