|
@@ -238,27 +238,56 @@ func (r *webForwardingRepository) GetDomainCount(ctx context.Context, hostId int
|
|
}
|
|
}
|
|
|
|
|
|
// 获取IP数量等于1的IP
|
|
// 获取IP数量等于1的IP
|
|
|
|
+
|
|
func (r *webForwardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
|
|
func (r *webForwardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
|
|
if len(ips) == 0 {
|
|
if len(ips) == 0 {
|
|
return []v1.IpCountResult{}, nil
|
|
return []v1.IpCountResult{}, nil
|
|
}
|
|
}
|
|
|
|
+
|
|
pipeline := []bson.M{
|
|
pipeline := []bson.M{
|
|
|
|
+ // 第 1 步: $unwind - 展开 backend_list 数组
|
|
|
|
+ // 将包含多个 backend 对象的文档拆分成多条,每条只包含一个 backend 对象。
|
|
|
|
+ {
|
|
|
|
+ "$unwind": "$backend_list",
|
|
|
|
+ },
|
|
|
|
+
|
|
|
|
+ // 第 2 步: $addFields - 添加一个新字段用于存放解析出的 IP
|
|
|
|
+ // 我们需要从 "ip:port" 格式的 addr 字段中把 ip 提取出来。
|
|
|
|
+ // 使用 $split 操作符按 ":" 分割字符串,然后用 $arrayElemAt 取第一个元素。
|
|
|
|
+ {
|
|
|
|
+ "$addFields": bson.M{
|
|
|
|
+ "extracted_ip": bson.M{
|
|
|
|
+ "$arrayElemAt": []interface{}{
|
|
|
|
+ bson.M{"$split": []string{"$backend_list.addr", ":"}},
|
|
|
|
+ 0,
|
|
|
|
+ },
|
|
|
|
+ },
|
|
|
|
+ },
|
|
|
|
+ },
|
|
|
|
+
|
|
|
|
+ // 第 3 步: $match - 匹配我们关心的 IP
|
|
|
|
+ // 在上一步创建的 extracted_ip 字段上进行匹配。
|
|
{
|
|
{
|
|
"$match": bson.M{
|
|
"$match": bson.M{
|
|
- "ip": bson.M{"$in": ips},
|
|
|
|
|
|
+ "extracted_ip": bson.M{"$in": ips},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
|
|
+
|
|
|
|
+ // 第 4 步: $group - 按解析出的 IP 地址进行分组和计数
|
|
{
|
|
{
|
|
"$group": bson.M{
|
|
"$group": bson.M{
|
|
- "_id": "$ip",
|
|
|
|
|
|
+ "_id": "$extracted_ip", // 使用我们新创建的 extracted_ip 字段作为分组依据
|
|
"count": bson.M{"$sum": 1},
|
|
"count": bson.M{"$sum": 1},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
|
|
+
|
|
|
|
+ // 第 5 步: $project - 格式化最终输出
|
|
|
|
+ // 这个阶段和之前一样,只是为了让输出结果更清晰,并匹配 Go 结构体。
|
|
{
|
|
{
|
|
"$project": bson.M{
|
|
"$project": bson.M{
|
|
- "_id": 0, // 不输出默认的_id
|
|
|
|
- "ip": "$_id", // 将分组的_id字段重命名为ip
|
|
|
|
- "count": 1, // 保留count字段
|
|
|
|
|
|
+ "_id": 0,
|
|
|
|
+ "ip": "$_id",
|
|
|
|
+ "count": 1,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
@@ -267,7 +296,8 @@ func (r *webForwardingRepository) GetIpCountByIp(ctx context.Context, ips []stri
|
|
// 使用 qmgo 执行聚合查询
|
|
// 使用 qmgo 执行聚合查询
|
|
err := r.mongoDB.Collection("web_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
|
|
err := r.mongoDB.Collection("web_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
|
|
if err != nil {
|
|
if err != nil {
|
|
- return nil, fmt.Errorf("聚合查询失败: %w", err)
|
|
|
|
|
|
+ // 加上错误包装,方便调试
|
|
|
|
+ return nil, fmt.Errorf("聚合查询 web_forwarding_rules 失败: %w", err)
|
|
}
|
|
}
|
|
|
|
|
|
return results, nil
|
|
return results, nil
|