Database
[{"from":"perry","to":"lois","type":"colleague",/** this data is repeated in every document*/"other data":"blah","other data1":"more blah","other data2":"even more blah"},{"from":"lois","to":"perry","type":"colleague"},{"from":"clark","to":"lois","type":"colleague"},{"from":"lois","to":"clark","type":"colleague"},{"from":"perry","to":"clark","type":"colleague"},{"from":"clark","to":"perry","type":"colleague"},{"from":"superman","to":"lois","type":"friend"},{"from":"lois","to":"superman","type":"friend"},{"from":"lois","to":"anonymousNewsSource1","type":"source"},{"from":"anonymousNewsSource1","to":"lois","type":"source"},{"from":"anonymousNewsSource2","to":"lois","type":"source"},{"from":"lois","to":"anonymousNewsSource2","type":"source"},{"from":"luthor","to":"superman","type":"enemy"},{"from":"superman","to":"luthor","type":"enemy"},{"from":"batman","to":"superman","type":"associate"},{"from":"superman","to":"batman","type":"associate"},{"from":"jimmy","to":"superman","type":"friend"},{"from":"superman","to":"jimmy","type":"friend"},{"from":"badguy1","to":"luthor","type":"associate"},{"from":"luthor","to":"badguy1","type":"associate"},{"from":"badguy1","to":"badguy2","type":"associate"},{"from":"badguy2","to":"badguy1","type":"associate"},{"from":"otis","to":"superman","type":"enemy"},{"from":"superman","to":"otis","type":"enemy"}]
Query
db.collection.aggregate([{$match:{from:"superman"}},{/**reduce size of query*/"$project":{"to":1,"from":1,"_id":0}},{$graphLookup:{from:"collection",startWith:"superman",connectFromField:"from",connectToField:"to",maxDepth:3,depthField:"degree",as:"connections"}},{/**reduce size of the array*/"$project":{"connections.to":1,"connections.degree":1}},{$unwind:"$connections"},{$group:{/**groups the documents by degree, which is the value of the depthField parameter added in the previous stage*/_id:"$connections.degree",connections:{/**creates an array of unique "to" values for each degree group.*/$addToSet:"$connections.to"}}},{$sort:{/**sorts the documents by _id, which is the degree field added in the $graphLookup stage.*/_id:1}},]/**, {* readPreference: "secondaryPreferred",* allowDiskUse: true* }*/)