Database
[{"collection":"players","count":100,"content":{"_id":{"type":"autoincrement","autoType":"int","startInt":0},"firstname":{"type":"faker","method":"FirstName"},"lastname":{"type":"faker","method":"LastName"}}},{"collection":"matches","count":10,"content":{"_id":{"type":"autoincrement","autoType":"int","startInt":0},"teamA":{"type":"array","minLength":8,"maxLength":12,"arrayContent":{"type":"int","minInt":0,"maxInt":49}},"teamB":{"type":"array","minLength":8,"maxLength":12,"arrayContent":{"type":"int","minInt":50,"maxInt":99}}}}]
Query
db.players.aggregate([{"$lookup":{"from":"matches","let":{"myId":"$_id"},"pipeline":[{"$match":{"$expr":{"$in":["$$myId",{"$setUnion":["$teamA","$teamB"]}]}}},{"$count":"numMatches"}],"as":"matchCount"}},{"$set":{"matches":{"$ifNull":[{"$first":"$matchCount.numMatches"},0]}}},{"$unset":"matchCount"}])