Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
How to unset objects in MongoDB?
To unset objects in MongoDB, use $unset. Let us create a collection with documents −
> db.demo348.insertOne(
... {
... "details": {
... "studentDetails":
... {
... StudentName: "Robert"
... }
... }
...
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e553556f8647eb59e5620b2")
}
> db.demo348.insertOne(
... {
... "details": {
... "studentDetails":
... {
... StudentName: "Mike"
... }
... }
...
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e553563f8647eb59e5620b3")
}
Display all documents from a collection with the help of find() method −
> db.demo348.find();
This will produce the following output &mius;
{ "_id" : ObjectId("5e553556f8647eb59e5620b2"), "details" : { "studentDetails" : { "StudentName" : "Robert" } } }
{ "_id" : ObjectId("5e553563f8647eb59e5620b3"), "details" : { "studentDetails" : { "StudentName" : "Mike" } } }
Following is the query to unset objects −
> db.demo348.update({},{$unset: { "details.studentDetails": ""}},{multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Display all documents from a collection with the help of find() method −
> db.demo348.find();
This will produce the following output −
{ "_id" : ObjectId("5e553556f8647eb59e5620b2"), "details" : { } }
{ "_id" : ObjectId("5e553563f8647eb59e5620b3"), "details" : { } }Advertisements