I have a collection made like this
[
{timestamp: xxx, type:'start'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'start'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'log'}
]
how do I aggregate the start event and the log event until but not including the next start?
the result should be something like this
something like this
{
events:[
{timestamp: xxx, type:'start'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'log'}
]
},
{
events:[
{timestamp: xxx, type:'start'},
{timestamp: xxx, type:'log'},
{timestamp: xxx, type:'log'}
]
}
2
Answers
It is a bit difficult, because the way you retracted your data makes your question pointless.
I guess,
timestamp
is a sequence of events. In this case a solution could be this one:Mongo Playground
Another solution is this one:
Mongo Playground
Assumption: the timestamp field is "sortable" type
You can use
$setWindowFields
to compute "grouping" for the events. The idea is to find the max timestamp withstart
in the window range of[unbounded, current]
(i.e. find in the documents before and in current document with a$max
). After computing the "grouping", just do a simple$group
to put the events together in an array.Mongo Playground
P.S. Your expected result form may suffer from MongoDB 16MB document size if a single grouping contains too many records.