从mongodb聚合中的数组中获取所有可能的组合🚀; [英] Get all possible combinations from array in MongoDB aggregation 🚀
本文介绍了从mongodb聚合中的数组中获取所有可能的组合🚀;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据数组中相同的值进行聚合($group
)?不是一次全部,但很少或全部(如果有)。我可以用一个单词完成$group
,但我还需要所有可能的变体.
采集示例:
{"keywords": ["gta", "distribution", "keys"]}
{"keywords": ["gta", "online", "moto", "races"]}
{"keywords": ["gta", "online", "samp"]}
结果示例:
- -3个匹配项(&Q;GTA&Q;-3个匹配项)
- 在线&q;-2个匹配项
- GTA Online&Quot;-2个匹配项
推荐答案
您可以使用$reduce
从数组中提取所有对的组合。我已从this post开始,并添加了当前项目$unwind
初始数组并计算项目数:
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 }
}
}
])
输出:
{ "_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 }
如果需要更多组合,您可能需要更新上面的$reduce
阶段
这篇关于从mongodb聚合中的数组中获取所有可能的组合🚀;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文