代码之家  ›  专栏  ›  技术社区  ›  italktothewind

使用Mongo聚合框架的共现计数

  •  0
  • italktothewind  · 技术社区  · 5 年前

    我有与客户交互的产品的以下文档(无重复产品):

    { "client_interactions": [{"productType": "A", "productId": "1"}, {"productType": "A", "productId": "2"}, {"productType": "B", "productId": "9"}]}
    { "client_interactions": [{"productType": "A", "productId": "1"}, {"productType": "A", "productId": "2"}]}
    { "client_interactions": [{"productType": "A", "productId": "1"}, {"productType": "A", "productId": "3"}, {"productType": "C", "productId": "10"}]}
    

    比如:

    { "co-ocurrences-count" : { "1" : [{ "2": 2}, { "3" : 1}]}, { "2" : [{ "1": 2}]}, { "3" : [{ "1": 1}]}}
    

    我有一个使用map reduce javascript函数的解决方案,但我真的希望它能使用MongoDB聚合框架来实现,有可能吗?

    提前谢谢。

    0 回复  |  直到 5 年前
        1
  •  1
  •   mickl    5 年前

    聚合相当长,但它是有效的。这个想法是你需要建立一对 (x,y) 基于你的 client_interactions 数组。可以使用 $reduce $map . 那你就得跑了 $unwind 还有一些 $group $arrayToObject

    db.collection.aggregate([
        {
            $addFields: {
                "client_interactions": {
                    $filter: { input: "$client_interactions", cond: { $eq: [ "$$this.productType", "A" ] } }
                }
            }
        },
        {
            $project: {
                a: {
                    $reduce: {
                        input: "$client_interactions",
                        initialValue: [],
                        in: {
                            $concatArrays: [
                                "$$value",
                                { $map: { input: "$client_interactions", as: "c",  in: { x: "$$this.productId", y: "$$c.productId" } } }
                            ]
                        }
                    }
                }
            }
        },
        {
            $unwind: "$a"
        },
        {
            $match: {
                $expr: {
                    $ne: [ "$a.x", "$a.y" ]
                }
            }
        },
        {
            $sort: {
                "a.x": 1,
                "a.y": 1
            }
        },
        {
            $group: {
                _id: "$a",
                count: { $sum: 1 }
            }
        },
        {
            $group: {
                _id: "$_id.x",
                arr: { $push: { k: "$_id.y", v: "$count" } }
            }
        },
        {
            $group: {
                _id: null,
                "co-ocurrences-count": { $push: { k: "$_id", v: { $arrayToObject: "$arr" } } }
            }
        },
        {
            $project: {
                _id: 0,
                "co-ocurrences-count": { $arrayToObject: "$co-ocurrences-count" }
            }
        }
    ])
    

    Mongo Playground