sql >> Database >  >> NoSQL >> MongoDB

Haal alle mogelijke combinaties uit de array in MongoDB-aggregatie

Je zou $reduce kunnen gebruiken om alle combinaties van paren uit een array te extraheren. Ik ben begonnen vanaf dit bericht en ik heb het huidige item toegevoegd, $unwind theinitial array en tel de 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 }
        }
    }
])

Uitgang :

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

Als je meer combinaties nodig hebt, moet je mogelijk de $reduce . updaten podium boven




  1. Hoe het .bson-bestandsformaat op mongodb te importeren

  2. Node JS Redis Clientverbinding Opnieuw proberen

  3. Redis scan sleutels overslaan

  4. Inleiding tot gegevenslocatie in Hadoop MapReduce