sql >> Base de Datos >  >> NoSQL >> MongoDB

Conteo de co-ocurrencia usando el marco de agregación de Mongo

La agregación es bastante larga pero funciona. La idea es que necesitas construir pares (x,y) basado en sus client_interactions formación. Se puede hacer usando $reduce y $map . Luego debe ejecutar $unwind y un par de $group etapas para "bobinar" sus datos agregados. También necesita $arrayToObject para construir sus llaves dinámicamente.

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

Patio de juegos Mongo