使用Go监听MongoDB Change Stream时如何获取插入事件中的数据
解决Go中MongoDB Change Stream获取嵌套字段的问题
从你给出的Change Stream输出可以看到,pod_name、total_container_count这些字段并不是直接在顶层的changeStream.Current中,而是嵌套在**fullDocument**子文档里。你直接调用changeStream.Current.Lookup("pod_name")自然找不到对应元素。
解决方案一:通过嵌套Lookup获取字段
直接修改循环内的代码,先提取fullDocument子文档,再从中获取目标字段:
for changeStream.Next(context.TODO()) { fmt.Println(changeStream.Current) // 先获取fullDocument子文档 fullDocVal := changeStream.Current.Lookup("fullDocument") fullDoc, ok := fullDocVal.M() if !ok { fmt.Println("无法获取fullDocument子文档") continue } // 提取pod_name字段 podNameVal := fullDoc.Lookup("pod_name") podName, ok := podNameVal.StringValueOK() if ok { fmt.Printf("POD name is: %s\n", podName) } else { fmt.Println("未找到pod_name字段") } // 提取total_container_count字段 containerCountVal := fullDoc.Lookup("total_container_count") containerCount, ok := containerCountVal.Int64OK() if ok { fmt.Printf("Total container count: %d\n", containerCount) } else { fmt.Println("未找到total_container_count字段") } }
解决方案二:反序列化为结构体(更推荐)
定义匹配Change Stream事件结构的结构体,将changeStream.Current反序列化进去,代码可读性更强、类型更安全:
// 定义对应Change Stream事件的结构体 type ChangeStreamEvent struct { FullDocument struct { PodName string `bson:"pod_name"` TotalContainerCount int `bson:"total_container_count"` // 可根据需求添加其他字段 } `bson:"fullDocument"` } // 在循环中执行反序列化 for changeStream.Next(context.TODO()) { var event ChangeStreamEvent err := changeStream.Decode(&event) if err != nil { fmt.Printf("反序列化失败: %v\n", err) continue } fmt.Printf("POD name is: %s\n", event.FullDocument.PodName) fmt.Printf("Total container count: %d\n", event.FullDocument.TotalContainerCount) }
注意事项
- 处理
Lookup或Decode时必须做存在性/错误检查,避免空指针或类型转换panic - 如果MongoDB文档字段类型与示例不同(比如
total_container_count是浮点型),需对应调整结构体字段类型
内容的提问来源于stack exchange,提问作者Jananath Banuka
相关产品推荐
相关产品推荐

