MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Conteggi di co-occorrenza con l'aggregation framework di MongoDB

La pipeline è lunga ma fa il suo lavoro. L'idea è costruire coppie (x,y) dal tuo array client_interactions usando $reduce e $map, poi $unwind e un paio di fasi $group per ricomporre i risultati. $arrayToObject costruisce le chiavi dinamicamente alla fine.

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

Il match $ne elimina le coppie con sé stesse, e le due fasi finali di group rimodellano i conteggi piatti delle coppie in un oggetto annidato con chiave l'id del prodotto.

Mongo Playground