I am currently dealing with a set of in-game-events for various matches. In the game it is possible to kill enemies and purchase items in a shop.
What I have been trying to do right now, is to count the number of kills that have occured in a single match up until every purchasing event.
{
"_id" : ObjectId("5988f89ae5873exxxxxxx"),
"gameId" : NumberLong(2910126xxx)
"participantId" : 3,
"type" : "ITEM_PURCHASED",
"timestamp" : 656664 },
{
"_id" : ObjectId("5988f89ae5873exxxxxxx"),
"gameId" : NumberLong(2910126xxx)
"participantId" : 3,
"victimId" : 9,
"type" : "ENEMY_KILLED",
"timestamp" : 745245 },
{
"_id" : ObjectId("5988f89ae5873exxxxxxx"),
"gameId" : NumberLong(2910126xxx)
"participantId" : 3,
"victimId" : 7,
"type" : "ENEMY_KILLED",
"timestamp" : 746223 },
{
"_id" : ObjectId("5988f89ae5873exxxxxxx"),
"gameId" : NumberLong(2910126xxx)
"participantId" : 3,
"type" : "ITEM_PURCHASED",
"timestamp" : 840245 },
In which this is a desired outcome for me:
{
"_id" : ObjectId("5988f89ae5873exxxxxxx"),
"gameId" : NumberLong(2910126xxx)
"participantId" : 3,
"type" : "ITEM_PURCHASED",
"timestamp" : 656664,
"kills": 0 },
{
"_id" : ObjectId("5988f89ae5873exxxxxxx"),
"gameId" : NumberLong(2910126xxx)
"participantId" : 3,
"type" : "ITEM_PURCHASED",
"timestamp" : 840245 ,
"kills": 2 }
Although I am inclined to think that this is quite impossible, I am not yet that experienced with all the capabilities mongo offers.
Is there a way to count occurrances of certain values up until the appearance of an purchasing event?
try this aggregation
$match
- filter by gameId$sort
- order documents by timestamp$group
- accumulate all matched to an array$addFields
-$reduce
to calculate kills, filter and map kills to document$unwind
- flat array to get original document structure$replaceRoot
- move data to top level as in original structurepipeline
collection
result