score:1

Try below aggregation:

db.col.aggregate([
    {
        $group: {
            _id: null,
            nodes: {
                $push: { id: "$id", name: "$name", company: "$company", token: "$token", node_time: { $ifNull: [ "$node_time", "$time" ] } }
            },          
            links: { $push: { links: "$links", id: "$id", link_time: { $ifNull: [ "$node_time", "$time" ] } } }
        }
    },
    {
        $project: {
            _id: 0,
            nodes: 1,
            links: {
                $reduce: {
                    input: "$links",
                    initialValue: [],
                    in: {
                        $concatArrays: [ "$$value", {
                            $map: {
                                input: "$$this.links",
                                as: "link",
                                in: {
                                    source: "$$this.id",
                                    target: "$$link",
                                    link_time: "$$this.link_time"
                                }
                            }
                        } ]
                    }
                }
            }
        }
    }
])

Basically it looks like you want to merge all your documents into one result so you should use $group with constant _id value like null. Then it's easy to get nodes value since it will be flat array after first step. The problem is with links as it's an array of arrays so you need $map and $reduce to flatten that field.


Related Query