Database
[{_id:1,"key":[{"key2":[{"key3":[{}]}]}]},{_id:2,"key4":2}]
Query
db.collection.aggregate([{$set:{n1:{$objectToArray:"$$ROOT"}}},{$unwind:{path:"$n1",preserveNullAndEmptyArrays:true}},{$unwind:{path:"$n1.v",preserveNullAndEmptyArrays:true}},{$set:{key_array:["$n1.k"],n2:{$cond:{if:{$eq:[{$type:"$n1.v"},"object"]},then:{$objectToArray:"$n1.v"},else:null}}}},{$unwind:{path:"$n2",preserveNullAndEmptyArrays:true}},{$unwind:{path:"$n2.v",preserveNullAndEmptyArrays:true}},{$set:{key_array:{$concatArrays:["$key_array",["$n2.k"]]},n3:{$cond:{if:{$eq:[{$type:"$n2.v"},"object"]},then:{$objectToArray:"$n2.v"},else:null}}}},{$unwind:{path:"$n3",preserveNullAndEmptyArrays:true}},{$unwind:{path:"$n3.v",preserveNullAndEmptyArrays:true}},{$set:{key_array:{$concatArrays:["$key_array",["$n3.k"]]}}},{$group:{_id:"$_id",key_array:{"$addToSet":"$key_array"}}},{$set:{key_array:{$reduce:{input:"$key_array",initialValue:[],in:{$concatArrays:["$$value","$$this"]}}}}},{$unwind:"$key_array"},{$match:{key_array:{$ne:null}}},{$group:{_id:"$_id",key_array:{$addToSet:"$key_array"}}}])