Go Mongo驱动聚合查询报Use of undefined variable: this错误
问题报错
Golang对接MongoDB官方驱动执行聚合查询时抛出错误:
Invalid $set :: caused by :: Use of undefined variable: this
相同逻辑的聚合语句在Mongo Shell中可正常执行,初步定位问题与$$this变量识别有关。
报错根因
问题出在Go端BSON结构的写法错误:
- Mongo聚合语句中每一组大括号
{}对应一个BSON文档对象,在Go官方Mongo驱动中需要用bson.D(有序文档)或bson.M(无序文档)类型表示,单个bson.E仅代表文档内的一个键值对,不能直接作为完整文档使用 - 原代码所有嵌套聚合操作符的位置都直接传入了单个
bson.E,导致驱动序列化后的BSON结构和预期聚合管道完全不符 - 结构异常后Mongo解析
$map操作时,无法正确识别$$this是$map迭代上下文的内置变量,最终抛出变量未定义的错误
修复代码
把所有代表完整BSON文档的位置,从单个bson.E替换为包裹对应键值对的bson.D即可,修复后的完整Pipeline代码如下:
pipeline := mongo.Pipeline{ // $lookup关联products表 bson.D{{Key: "$lookup", Value: bson.M{ "from": "products", "localField": "product_types.product_id", "foreignField": "_id", "as": "productInterestData", }}}, // $set处理product_types数组,关联匹配的product数据 bson.D{{Key: "$set", Value: bson.D{ {Key: "product_types", Value: bson.D{ {Key: "$map", Value: bson.D{ {Key: "input", Value: "$product_types"}, {Key: "in", Value: bson.D{ {Key: "$mergeObjects", Value: bson.A{ "$$this", bson.D{{Key: "product", Value: bson.D{ {Key: "$arrayElemAt", Value: bson.A{ "$productInterestData", bson.D{{Key: "$indexOfArray", Value: bson.A{"$productInterestData._id", "$$this.product_id"}}}, }}, }}}, }}, }}, }}, }}, }}}, // 清理临时关联字段 bson.D{{Key: "$unset", Value: "productInterestData"}}, } cursor, err := ctx.Store.GetCollection(ctx, &models.Interest{}).Aggregate(c, pipeline) if err != nil { utils.Log(c, "warn", err) return }
注意事项
- 写Mongo聚合管道时优先使用
bson.D而非bson.M,bson.D保留字段顺序,可以避免部分对字段顺序敏感的聚合操作出现隐性异常 - 对照Mongo Shell的聚合语句写Go代码时,每遇到一层
{}就对应一层bson.D{}包裹,就不会出现结构写错的问题
内容的提问来源于stack exchange,提问作者Adrien Chapelet
相关产品推荐
相关产品推荐

