How can I delete an item from an Object in MongoDB?


To delete an item from an object in MongoDB, use $unset. Let us create a collection with documents −

> db.demo467.insertOne(
... {
... _id:101,
... "Information":{"Name":"Chris"}
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo467.insertOne(
... {
... _id:102,
... "Information":{"Name":"David"}
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }

Display all documents from a collection with the help of find() method −

> db.demo467.find();

This will produce the following output −

{ "_id" : 101, "Information" : { "Name" : "Chris" } }
{ "_id" : 102, "Information" : { "Name" : "David" } }

Following is the query to delete an item from an Object −

> db.demo467.update({_id:102},{$unset: {"Information.Name":1}},{multi: true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo467.find();

This will produce the following output −

{ "_id" : 101, "Information" : { "Name" : "Chris" } }
{ "_id" : 102, "Information" : { } }

Updated on: 11-May-2020

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements