Mongodb递增合并

0lvr5msh  于 2022-12-18  发布在  Go
关注(0)|答案(1)|浏览(93)

如何将以下“点击”集合合并到“会话”集合中:
点击次数:

{session_id: 2, time: 12}, 
{session_id: 2, time: 12.1}, 
{session_id: 3, time: 13},

会议:

{session_id:1, start_time: 1, clicks: 1},
{session_id:2, start_time: 2, clicks: 1}

因此集合“会话”变为:

{session_id: 1, start_time: 1, clicks: 1},  // "old" sessions data remains as is 
{session_id: 2, start_time: 2, clicks: 3}, // start_time is still 2, clicks have incremented
{session_id: 3, start_time: 13, clicks: 1} // a session with a new session_id is added


并且使得当更多的点击被添加到“点击”集合并在{time: { $gt: 13 }}上对其进行过滤时可以重复该过程(以避免再次处理相同的点击)。

rdrgkggo

rdrgkggo1#

假设session_id是一个唯一字段(由唯一索引强制执行),您可以先使用$groupclicks记录按session_id分组,然后将$merge分组到sessions集合中。

db.clicks.aggregate([
  {
    $group: {
      _id: "$session_id",
      start_time: {
        $min: "$time"
      },
      clicks: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      session_id: "$_id",
      start_time: 1,
      clicks: 1
    }
  },
  {
    "$merge": {
      "into": "sessions",
      "let": {
        delta: "$clicks"
      },
      "on": "session_id",
      "whenMatched": [
        {
          $set: {
            clicks: {
              $add: [
                "$clicks",
                "$$delta"
              ]
            }
          }
        }
      ],
      "whenNotMatched": "insert"
    }
  }
])

Mongo Playground

相关问题