Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to exclude array type field value in MongoDB?
To exclude array type field values in MongoDB, you can use the $unset operator or JavaScript's delete() function with forEach(). This allows you to remove specific fields from array elements while preserving the array structure.
Syntax
// Method 1: Using $unset operator
db.collection.updateMany(
{},
{ $unset: { "arrayField.$[].fieldName": "" } }
);
// Method 2: Using forEach with delete()
db.collection.find().forEach(function(doc) {
doc.arrayField.forEach(function(element) {
delete element.fieldName;
});
db.collection.save(doc);
});
Sample Data
db.demo464.insertOne({
"id": "101",
"details": [
{
"Name": "Chris"
},
{
"Name": "David"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e7f8832cb66ccba22cc9dda")
}
Method 1: Using $unset Operator (Recommended)
db.demo464.updateOne(
{ "id": "101" },
{ $unset: { "details.$[].Name": "" } }
);
Method 2: Using forEach with delete()
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);
});
Verify Result
db.demo464.find();
{
"_id": ObjectId("5e7f8832cb66ccba22cc9dda"),
"id": "101",
"details": [
{ },
{ }
]
}
Key Points
- The
$unsetoperator is more efficient for bulk operations on array fields. - The
forEach()method provides more control but requires manual document saving. - Both methods preserve the array structure while removing specified fields.
Conclusion
Use $unset with the $[] positional operator for efficient field removal from array elements. The forEach() approach offers more flexibility but requires explicit saving of modified documents.
Advertisements
