Anda dapat menggunakan $reduce
untuk mengekstrak semua kombinasi pasangan dari array. Saya sudah mulai dari postingan ini
dan saya telah menambahkan item saat ini, $unwind
array awal dan hitung itemnya :
db.test.aggregate([
{
$project: {
pairs: {
$reduce: {
input: { $range: [0, { $size: "$keywords" }] },
initialValue: [],
in: {
$concatArrays: [
"$$value",
[[{ $arrayElemAt: ["$keywords", "$$this"] }]],
{
$let: {
vars: { i: "$$this" },
in: {
$map: {
input: { $range: [{ $add: [1, "$$i"] }, { $size: "$keywords" }] },
in: [{ $arrayElemAt: ["$keywords", "$$i"] }, { $arrayElemAt: ["$keywords", "$$this"] }]
}
}
}
}
]
}
}
}
}
}, {
$unwind: "$pairs"
}, {
$group: {
_id: "$pairs",
count: { $sum: 1 }
}
}
])
Keluaran :
{ "_id" : [ "online", "samp" ], "count" : 1 }
{ "_id" : [ "gta", "samp" ], "count" : 1 }
{ "_id" : [ "online", "races" ], "count" : 1 }
{ "_id" : [ "moto", "races" ], "count" : 1 }
{ "_id" : [ "gta", "keys" ], "count" : 1 }
{ "_id" : [ "races" ], "count" : 1 }
{ "_id" : [ "gta", "distribution" ], "count" : 1 }
{ "_id" : [ "samp" ], "count" : 1 }
{ "_id" : [ "distribution", "keys" ], "count" : 1 }
{ "_id" : [ "gta" ], "count" : 3 }
{ "_id" : [ "online" ], "count" : 2 }
{ "_id" : [ "keys" ], "count" : 1 }
{ "_id" : [ "gta", "online" ], "count" : 2 }
{ "_id" : [ "moto" ], "count" : 1 }
{ "_id" : [ "online", "moto" ], "count" : 1 }
{ "_id" : [ "distribution" ], "count" : 1 }
{ "_id" : [ "gta", "moto" ], "count" : 1 }
{ "_id" : [ "gta", "races" ], "count" : 1 }
Jika Anda membutuhkan lebih banyak kombinasi, Anda mungkin perlu memperbarui $reduce
panggung di atas