Sub-document to new document along with existing main document

Actually, the code I provided above, will provide you the exact result that you want.
You just need to put everything into 1 single aggregation:

db.your_collection.aggregate([
  { $group: { ... } },
  { $set: { ... } },
  { $project: { ... } },
  { $unwind: { ... } },
  { $replaceWith: ... }
]);

Also, consider to restructure your documents like this:

{
   _id,
   parentId,
   name
}

With this structure, every object, parent or child will be in a separate documents in the collection. If parentId is not null, then this document is a child, otherwise it is parent. Also, it will be easy to do a $lookup of children by parentId value :wink: