Database

[{"_id":ObjectId("617d9ed5cfd28c2c5fd8554c"),"title":"Category 1","children":[ObjectId("617d9ed5cfd28c2c5fd8554d"),ObjectId("617d9ed5cfd28c2c5fd8554e")]},{"_id":ObjectId("617d9ed5cfd28c2c5fd8554d"),"title":"Category 2","children":[ObjectId("617d9ed5cfd28c2c5fd8554e")]},{"_id":ObjectId("617d9ed5cfd28c2c5fd8554e"),"title":"Category 3","children":[]},{"_id":ObjectId("617d9ed5cfd28c2c5fd8554f"),"title":"Category 4","children":[ObjectId("617d9ed5cfd28c2c5fd8554c")]}]

Query

db.collection.aggregate([{"$group":{/** go through each document*/"_id":null,/** push all _id's (already unique)*/"ids":{"$push":"$_id"},/** this will be an array of arrays unfortunately*/"children":{"$addToSet":"$children"}}},{"$project":{/** don't need _id*/"_id":0,/** assign theIds as the output*/"theIds":{/** set difference = what's in ids but not in children*/"$setDifference":["$ids",{/** collapse children to a single flat array*/"$reduce":{"input":"$children","initialValue":[],"in":{"$concatArrays":["$$value","$$this"]}}}]}}}])

Result