Dynamically filter fields which might even be nested in a document

Need to filter “title” and “description” from the documents. This is just at the first level, but i also need to solve it for the nested documents.

{
    "_id" : "63dadc6753bfc516421c5958",
    "properties" : {
        "abc:id" : {
            "title" : "Identifier",
            "type" : "string",
            "description" : "Identity of the consumer"
        },
        "abc:authenticatedState" : {
            "description" : "The state this identity is authenticated",
            "type" : "string",
            "default" : "ambiguous",
            "enum" : [
                "ambiguous",
                "authenticated",
                "loggedOut"
            ]
        },
        "abc:primary" : {
            "title" : "Primary",
            "type" : "boolean",
            "default" : false,
            "description" : "description"
        }
    }
}

Output should not have “title” and “description” in its $project phase

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

Thank you @turivishal.
I was also able to get it working using the $map and $filter.

    {
    $project: {
      _id: 1,
      properties: {
        $map: {
          input: "$properties",
          in: {
            k: "$$this.k",
            v: {
              $filter: {
                input: "$$this.v",
                cond: { $and: [{$ne: ["$$this.k", "title"]},{$ne: ["$$this.k", "description"]}]  }
              }
            }
          }
        }
      }
    }
  }
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.