Database
[{"id":"SOMEID","03":{"17":{"id":"xxx","name":"test","lastSeen":"2025-03-17","someotherkey":"value"},"18":{"id":"xxx","name":"myname","lastSeen":"2025-03-18","someotherkey":"value"}}},{"id":"SOMEID","04":{"20":{"id":"xxx","name":"vmWBPrd01VANZEAL","lastSeen":"2025-04-20","someotherkey":"value"},"21":{"id":"123","dnsName":"vmWBPrd01VANZEAL","lastSeen":"2025-04-20","someotherkey":"value"}}}]
Query
db.collection.aggregate([{$replaceWith:{_id:"$_id",id:"$id",doc:{/** assumes one month per doc (one top-level field)*/$first:{$filter:{input:{$objectToArray:"$$ROOT"},cond:{/** skip _id & id since they are separate*/$eq:[{$indexOfArray:[["_id","id"],"$$this.k"]},-1]}}}}}},{/** the input $doc can be combined* with the stage above*/$set:{doc:{v:{$objectToArray:"$doc.v"}}}},{$match:{$or:[{"doc.v.v.name":{$regex:"vmWBPrd01VANZEAL"}},{"doc.v.v.ip":"vmWBPrd01VANZEAL"}]/** SEARCH TERM HERE*/}},{/** undo the transformations*/$set:{doc:[{k:"$doc.k",v:{$arrayToObject:"$doc.v"}}]}},{$replaceWith:{$mergeObjects:[{_id:"$_id"},{$arrayToObject:"$doc"}]}}])