Database

[{"03":{"17":{"id":"xxx","name":"myname","lastSeen":"2025-03-17","someotherkey":"value"},"18":{"id":"xxx","name":"myname","lastSeen":"2025-03-18","someotherkey":"value"}}},{"04":{"20":{"id":"xxx","name":"otherName","lastSeen":"2025-04-20","someotherkey":"value"}}}]

Query

db.collection.aggregate([{$replaceWith:{_id:"$_id",doc:{/** assumes one month per doc (one top-level field)*/$first:{$filter:{input:{$objectToArray:"$$ROOT"},cond:{/** skip _id since it's separate*/$ne:["$$this.k","_id"]}}}}}},{/** the input $doc can be combined* with the stage above*/$set:{doc:{v:{$objectToArray:"$doc.v"}}}},{$match:{/** SEARCH TERM HERE*/"doc.v.v.name":{$regex:"yna"}}},{/** undo the transformations*/$set:{doc:[{k:"$doc.k",v:{$arrayToObject:"$doc.v"}}]}},{$replaceWith:{$mergeObjects:[{_id:"$_id"},{$arrayToObject:"$doc"}]}}])

Result