我有类似的东西:`
[
{
....
tags : ["A","B"]
},
{
....
tags : ["A","B"]
},
{
....
tags : ["J","K"]
},
{
....
tags : ["A","B","C"]
}
]`
使用聚合框架,我想按数组组合进行分组以获得如下内容:
[
{
_id:["A","B"],
count : 3
},
{
_id:["J","K"],
count : 1
},
{
_id:["A","C"],
count : 1
},
{
_id:["B","C"],
count : 1
},
]
是否可以?提前致谢
询问
["V"] -> ["V" null]
(如果您不想用 null 计算对,您可以在最终结果中过滤掉)["A" "B" "C"]
将“A”与["B" "C"]
“B”与["A" "C"]
等(我们计算双倍,接下来将除以 2)["A" "B"] = ["B" "A"]
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"
}
}
} ]
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句