我有一个这样制作的集合
[
{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'}
]
如何聚合启动事件和日志事件,直到但不包括下一次启动?
结果应该是这样的 像这样的东西
{
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'}
]
}
这有点困难,因为你撤回数据的方式让你的问题毫无意义。
我猜,
timestamp
是一系列事件。在这种情况下,解决方案可能是这样的:
db.collection.aggregate([
{ $group: { _id: null, events: { $push: "$$ROOT" } } },
{
$project: {
events: {
$reduce: {
input: { $sortArray: { input: "$events", sortBy: { timestamp: 1 } } },
initialValue: [],
in: {
$concatArrays: ["$$value",
[{
$mergeObjects: ["$$this", {
branch: {
$cond: {
if: { $eq: ["$$this.type", 'start'] },
then: { $ifNull: [{ $add: [{ $last: "$$value.branch" }, 1] }, 0] },
else: { $last: "$$value.branch" }
}
}
}]
}]
]
}
}
}
}
},
{ $unwind: "$events" },
{ $group: { _id: "$events.branch", events: { $push: { timestamp: "$events.timestamp", type: "$events.type" } } } },
])