Mongodb 聚合两个事件之间的事件

问题描述 投票:0回答:1

我有一个这样制作的集合

[
  {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'}
  ]
}
mongodb aggregation-framework
1个回答
0
投票

这有点困难,因为你撤回数据的方式让你的问题毫无意义。

我猜,

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" } } } },
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.