Get all possible combinations from array in MongoDB aggregation 🚀

此生再无相见时 提交于 2020-12-06 16:18:09

问题


How to do aggregation ($group) by the same values ​​from the array? Not all at once, but few or all, if any. I can do $group by one word, but I also need all possible variations...

Collection example:

{"keywords": ["gta", "distribution", "keys"]}
{"keywords": ["gta", "online", "moto", "races"]}
{"keywords": ["gta", "online", "samp"]}

Result example:

  1. "gta" - 3 matches
  2. "online" - 2 matches
  3. "gta online" - 2 matches

回答1:


You could use $reduce to extract all combinations of pairs from an array. I've started from this post and I've added the current item, $unwind the initial array and count the items :

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 }
        }
    }
])

Output :

{ "_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 }

If you need more combinations, you may need to update the $reduce stage above



来源:https://stackoverflow.com/questions/64812637/get-all-possible-combinations-from-array-in-mongodb-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!