Database

[{"tags":["A","B"]},{"tags":["A","B"]},{"tags":["J","K"]},{"tags":["A","B","C"]},{"tags":["Z"]}]

Query

db.collection.aggregate([{"$set":{"tags":{"$cond":[{"$eq":[{"$size":"$tags"},1]},{"$concatArrays":["$tags",[null]]},"$tags"]}}},{"$set":{"a":{"$map":{"input":"$tags","in":{"member":"$$t","togetherWith":{"$setDifference":["$tags",["$$t"]]}},"as":"t"}}}},{"$unwind":{"path":"$a"}},{"$replaceRoot":{"newRoot":"$a"}},{"$unwind":{"path":"$togetherWith"}},{"$group":{"_id":{"$cond":[{"$lt":["$member","$togetherWith"]},["$member","$togetherWith"],["$togetherWith","$member"]]},"count":{"$sum":0.5}}},{"$set":{"count":{"$toInt":"$count"}}}])

Result