sql >> Database teknologi >  >> NoSQL >> MongoDB

MongoDB kører total som aggregering af tidligere poster indtil forekomst af værdi

prøv denne sammenlægning

  1. $match - filtrer efter gameId
  2. $sort - bestille dokumenter efter tidsstempel
  3. $group - akkumulere alle matchede til en matrix
  4. $addFields - $reduce for at beregne drab, filtrere og kortlægge drab for at dokumentere
  5. $unwind - flad array for at få original dokumentstruktur
  6. $replaceRoot - flyt data til topniveau som i den oprindelige struktur

pipeline

db.games.aggregate([
    {$match : {gameId : 1}},
    {$sort : {timestamp : 1}},
    {$group : {_id : "$gameId", data : {$push : "$$ROOT"}}},
    {$addFields : {data : {
        $reduce : {
            input : "$data",
            initialValue : {kills : [], data : [], count : 0},
            in : {
                count : {$sum : ["$$value.count", {$cond : [{$eq : ["$$this.type", "ENEMY_KILLED"]}, 1, 0]}]},
                data : { $concatArrays : [
                     "$$value.data", 
                     {$cond : [
                            {$ne : ["$$this.type", "ENEMY_KILLED"]}, 
                            [
                                {
                                    _id : "$$this._id",
                                    gameId : "$$this.gameId",
                                    participantId : "$$this.participantId",
                                    type : "$$this.type",
                                    timestamp : "$$this.timestamp",
                                    kills : {$sum : ["$$value.count", {$cond : [{$eq : ["$$this.type", "ENEMY_KILLED"]}, 1, 0]}]}
                                }
                            ],
                            []
                        ]}
                    ]}
                }
            }}
    }},
    {$unwind : "$data.data"},
    {$replaceRoot : {newRoot : "$data.data"}}
]).pretty()

indsamling

> db.games.find()
{ "_id" : 1, "gameId" : 1, "participantId" : 3, "type" : "ITEM_PURCHASED", "timestamp" : 656664 }
{ "_id" : 2, "gameId" : 1, "participantId" : 3, "victimId" : 9, "type" : "ENEMY_KILLED", "timestamp" : 745245 }
{ "_id" : 3, "gameId" : 1, "participantId" : 3, "victimId" : 7, "type" : "ENEMY_KILLED", "timestamp" : 746223 }
{ "_id" : 4, "gameId" : 1, "participantId" : 3, "type" : "ITEM_PURCHASED", "timestamp" : 840245 }

resultat

{
    "_id" : 1,
    "gameId" : 1,
    "participantId" : 3,
    "type" : "ITEM_PURCHASED",
    "timestamp" : 656664,
    "kills" : 0
}
{
    "_id" : 4,
    "gameId" : 1,
    "participantId" : 3,
    "type" : "ITEM_PURCHASED",
    "timestamp" : 840245,
    "kills" : 2
}
> 



  1. Hvordan kalder man funktion efter afslutning af asynkrone funktioner inde i loop?

  2. Mongo db c# driver - hvordan deltager man med id i samlingen?

  3. Hvordan laver jeg MongoDB konsol-stil forespørgsler i PHP?

  4. Tillykke med fødselsdagen Apache HBase! 10 års robusthed, stabilitet og ydeevne