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 $unset operator 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.

Updated on: 2026-03-15T03:04:17+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements