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" : { } }

Updated on: 02-Apr-2020

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements