How to exclude array type field value in MongoDB?


To exclude array type field value, use delete() in MongoDB. Let us create a collection with documents −

> db.demo464.insertOne(
... {
...
...    "id" : "101",
...    "details": [
...       {
...          Name:"Chris"
...       },
...       {
...          Name:"David"
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f8832cb66ccba22cc9dda")
}

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

> db.demo464.find();

This will produce the following output −

{ "_id" : ObjectId("5e7f8832cb66ccba22cc9dda"), "id" : "101", "details" : [ { "Name" : "Chris" }, {
"Name" : "David" } ] }

Following is the query to exclude array type field values −

> db.demo464.find({id: "101"}).forEach(function(mongoDocument) {
...
... var details = mongoDocument.details;
... for(var j = 0; j − details.length; ++j) {
... var array = details[j];
... delete (array["Name"]);
...
... }
... db.demo464.save(mongoDocument);
... });

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

> db.demo464.find();

This will produce the following output −

{ "_id" : ObjectId("5e7f8832cb66ccba22cc9dda"), "id" : "101", "details" : [ { }, { } ] }

Updated on: 11-May-2020

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements