MongoDB通过嵌套/子文档字段加入或查找

时间:2017-02-28 18:52:41

标签: mongodb

我有各种各样的活动,以及接收该活动的每小时统计数据。 我想使用$ lookup合并它们。请帮助我,关于如何在嵌套文档中执行此操作,其中event_id是我要查找的公共字段。

Events:
{
  "event_id"      : "1",     //Unique
  "event_name"    : "name1",
  "severity"      : "high",
  "type"          : "error"
}

Hourly_stats:  
{
   "hour"         : "2017O30123" //23rd hour
   incoming_events_during_this_hour : [
        {"event_id" : 1, "received" : 12},
        {"event_id" : 2, "received" : 14}, 
        {"event_id" : 3, "received" : 8},
   ]
}
{
   "hour"         : "2017O30124" //24th hour
   incoming_events_during_this_hour : [
        {"event_id" : 1, "received" : 16},
        {"event_id" : 2, "received" : 14}, 
        {"event_id" : 3, "received" : 8},
   ]
}

预期输出为:

After Lookup on Events with target collection Hourly_stats
    {
      "event_id"      : "1"
      "event_name"    : "name1",
      "severity"      : "high",
      "type"          : "error"
      incoming_events_during_this_hour : [
              {
               "hour"         : "2017O30123",
               {"event_id" : 1, "received" : 12},
              },
              {
               "hour"         : "2017O30124",
               {"event_id" : 1, "received" : 16},
              }
      ]
    }

OR as multiple rows (per hour basis)

    {
      "event_id"      : "1"
      "event_name"    : "name1",
      "severity"      : "high",
      "type"          : "error"
      incoming_events_during_this_hour : 
              {
               "hour"         : "2017O30123",
               {"event_id" : 1, "received" : 12},
              }
    }


    {
      "event_id"      : "1"
      "event_name"    : "name1",
      "severity"      : "high",
      "type"          : "error"
      incoming_events_during_this_hour : 
              {
               "hour"         : "2017O30124",
               {"event_id" : 1, "received" : 16},
              }
    }

1 个答案:

答案 0 :(得分:1)

您可以尝试以下聚合作为开始..您需要在hour添加匹配项,因为它会获取整个Hourly_stats集合。

以下查询会展开incoming_events_during_this_hour以获取event id并为每个事件分组incoming_events_during_this_hour,最后一步是查找事件信息。

db.Hourly_stats.aggregate([{
    $unwind: "$incoming_events_during_this_hour"
}, {
    $group: {
        _id: "$incoming_events_during_this_hour.event_id",
        incoming_events_during_this_hour: {
            $push: {
                hour: "$hour",
                "event_received": "$incoming_events_during_this_hour"
            }
        }
    }
}, {
    $lookup: {
        "from": "Events",
        "localField": "_id",
        "foreignField": "event_id",
        "as": "_id"
    }
}, {
    $project: {
        _id: 0,
        event: {
            $arrayElemAt: ["$_id", 0]
        },
        incoming_events_during_this_hour: 1
    }
}]);