Dynamically filter fields which might even be nested in a document

Hello @waykarp, Welcome to the MongoDB community forum,

You can try something like this,

  • use $objectToArray to convert an object to an array key-value pair
  • use projection 0 with non-required fields
  • use $arrayToObject to convert back to the object from the array
db.collection.aggregate([
  {
    $project: {
      properties: {
        $objectToArray: "$properties"
      }
    }
  },
  {
    $project: {
      "properties.v.description": 0,
      "properties.v.title": 0
    }
  },
  {
    $project: {
      properties: {
        $arrayToObject: "$properties"
      }
    }
  }
])
1 Like