

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" : [ ] }
- Related Questions & Answers
- MongoDB $push in nested array?
- Increment MongoDB value inside a nested array
- Get array items inside a MongoDB document?
- MongoDB Increment value inside nested array?
- MongoDB query to aggregate nested array
- MongoDB query to sort nested array?
- Update objects in a MongoDB documents array (nested updating)?
- Extract particular element in MongoDB within a Nested Array?
- Extract a particular element from a nested array in MongoDB
- MongoDB find by multiple array items?
- Query a nested field within an array with MongoDB
- Query array of nested string with MongoDB?
- How to create double nested array in MongoDB?
- Retrieve values from nested JSON array in MongoDB?
- Set filtering conditions for nested array in MongoDB
Advertisements