Skip to content

$unsetField

The $unsetField operator removes a field from a document dynamically.


📌 Syntax

{
  "$unsetField": {
    "field": <fieldName>,
    "input": <document>
  }
}
  • field: The field name to remove (string or expression)
  • input: The document to modify

✅ Base Example – Remove Field

📥 Input Document

{ "a": 1, "b": 2 }

📌 Expression

{
  "$unsetField": {
    "field": "b",
    "input": "$$ROOT"
  }
}

📤 Output

{ "a": 1 }

✅ Remove Dynamic Field

📥 Input Document

{ "fields": { "x": 1, "y": 2 }, "removeKey": "y" }

📌 Expression

{
  "$unsetField": {
    "field": "$removeKey",
    "input": "$fields"
  }
}

📤 Output

{ "x": 1 }

🧱 Ecommerce Example – Remove Obsolete Attribute

📌 Pipeline

[
  {
    "$project": {
      "product": "$name",
      "cleanAttributes": {
        "$unsetField": {
          "field": "legacyCode",
          "input": "$attributes"
        }
      }
    }
  }
]

📥 Input Document

{
  "name": "Backpack",
  "attributes": {
    "color": "Blue",
    "legacyCode": "DEPRECATED"
  }
}

📤 Output

{
  "product": "Backpack",
  "cleanAttributes": {
    "color": "Blue"
  }
}

🔧 Common Use Cases

  • Clean up deprecated or legacy fields
  • Sanitize sensitive data
  • Apply dynamic field deletions

  • $setField, $getField, $objectToArray, $project, $unset

🧠 Notes

  • Returns a new document with the field removed
  • Dynamic field names supported